edit:
thanks a lot ya'll. Have a great night/day
All I'm trying to do is have javascript change the image src in a table cell by checking the id of the cell.
I have looked at every single related question on stack overflow and their solution. For some reason, my code won't work. Most likely syntax/lack of sleep issue
This js script in a table, located right above the src I'm trying to change depending on things:
<script>
function getImage(){
return "http://i.imgur.com/s5WKBjy.png"; //i literally just want to see if this works and it isn't
}
document.onload = function(){
document.getElementById('homeimage').src = getImage();
};
</script>
<td colspan="3"><img style="width:110px;height:128px;" id = "homeimage" onload="getImage()"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimage"></td>
neither of the above work. With the onload = "getImage()" and without. Am I being dumb? There's got to be something obvious I'm missing.
As if you don't want to use any ID the you can use this method,
This code works for n number td's in your table....
window.onload = function()
{
var rows = document.getElementsByTagName("table")[0].rows;
tds = rows[0].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
tds[n].getElementsByTagName('img')[0].src = getImage();
}
}
function getImage(){
return "http://i.imgur.com/s5WKBjy.png";
}
<table>
<tr>
<td colspan="3"><img style="width:110px;height:128px;"></td>
<td colspan = "3"><img style="width:150px;height:128px;"></td>
</tr>
</table>
You can't have two images with the same id. Name one homeimage1 and the other one homeimage2 for instance.
We can't use same id more than once in a single web page. Use different ids.
2nd change doucment.onload to window.onload
function getImage(){
return "http://i.imgur.com/s5WKBjy.png";
}
window.onload = function(){
document.getElementById('homeimageA').src = getImage();
document.getElementById('homeimageB').src = getImage();
}
<td colspan="3"><img style="width:110px;height:128px;" id = "homeimageA" onload="getImage()"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id = "homeimageB"></td>
Things to note:
You have duplicate IDs, where IDs are should be unique.
You should use encodeURIComponent() to return the url value.
You don't have to use onload on the image itself.
You should bind the onload event on window object, that will do.
Before set the src just decodeURIComponent() to return value.
<td colspan="3"><img style="width:110px;height:128px;" id="homeimage1"></td>
<td colspan = "3"><img style="width:150px;height:128px;" id="homeimage2"></td>
Now changes in js:
<script>
function getImage(){
return encodeURIComponent("http://i.imgur.com/s5WKBjy.png"); //i literally just want to see if this works and it isn't
}
window.onload = function(){
document.getElementById('homeimage').src = decodeURIComponent(getImage());
};
</script>
Related
I want javascript to automatically add an incrementing numeric id for each of my td elements.
I want a script at the bottom of each HTML page to tell what first id will be input for that page and ++ automaticaly for each next td element. I tried a lot of things with for loop and something is missing with my appendChild method, i just can't make it work but i know i'm almost there.
If someone could give a hand, it would be greatly appreciated!
Here is how a manually enter those IDs each new month :
<tr>
<td id="603" class="offweekend"></td>
<td id="604" class="offmonth"></td>
<td id="605" class="offmonth"></td>
<td id="606" class="offmonth"></td>
<td id="607" class="offmonth"></td>
<td id="608" class="offmonth"></td>
<td id="609" class="weekend">1</td>
</tr>
<script>
tds = document.getElementsByTagName("td");
tdlength = tds.length;
firsttd = 603;
lasttd = firsttd + tdlength;
for (i = firsttd; i < lasttd; i++){
td.appendChild() //???That's where i'm confused, i'm i wrong
with this approach?
}
</script>
//Thank you, i'm still learning :)
Assuming that you have a variable firstValue that stores what the id of the first td should be, you can use this:
document.querySelectorAll("td").forEach((v,i)=>v.id=i+firstValue);
The querySelectorAll grabs all of the td elements in order as a NodeList.
v is the td element and i is the position of the element in the array
You don't need to use appendChild. You can simply iterate through the cells and set the id immediately.
let id = 603;
const cells = document.querySelectorAll('td');
cells.forEach(function(el) {
el.id = id++;
});
A small aside: I don't know your indended use but you might be better off using a data attribute for storing this information instead.
let id = 603;
const cells = document.querySelectorAll('td');
cells.forEach(function(el) {
el.setAttribute('data-id', id++);
});
My problem is the following:
I have created an array from a table I already have and stored the column I want into an array, and then stored it in the localStorage using JSON.stringify:
function createArray(){
var arrayPlayerName = [];
var count = 1;
while(count<=playerNum){
arrayPlayerName.push(document.getElementById('playertable').rows[count].cells[1].innerHTML);
count++;
}
localStorage.setItem("playerNameArray", JSON.stringify("arrayPlayerName"));
}
(playerNum is a variable with a fixed number used in other methods, and the "getElementById" works).
After that I want to show this data in another table in another HTML doc.
So, the following is my HTML code:
<table class="myTable">
<thead>
<tr class="row">
<th colspan="3">Array List</th>
</tr>
</thead>
</table>
And this is the script:
var storedPlayerArray = JSON.parse(localStorage.getItem("playerNameArray"));
tablegenerate (storedPlayerArray);
function tablegenerate (list) {
for(i=0; i<playerNum;i++){
var $formrow = '<tr><td>'+list[i]+'</td></tr>';
$('.myTable').append($formrow);
}
}
I am not sure what I'm doing wrong.. thanks in advance.
EDIT: I am calling the createArray function with a button, and I'm navigating to the second page with another button. The second page should load directly.
EDIT2: I have revised that the array is being stored and called properly on the second page, so the issue is now on the "tablegenerate" function.
EDIT
I think I found the problem try this:
var storedPlayerArray = JSON.parse(localStorage.getItem("playerNameArray"));
function tablegenerate (list) {
for(var i=0; i<list.length;i++){
var $formrow = $('<tr><td>'+list[i]+'</td></tr>');
$('.myTable').append($formrow);
}
}
$(document).ready(function(){
tablegenerate (storedPlayerArray);
})
You have an issue in your createArray function.. You are running JSON.stringify on a string instead of the array you want to store.
Change this:
localStorage.setItem("playerNameArray", JSON.stringify("arrayPlayerName"));
To this:
localStorage.setItem("playerNameArray", JSON.stringify(arrayPlayerName));
I am very new in JavaScript and I have the following problem to solve.
I have a table that contains this td cell:
<td class= "dateToConvert" width = "8.33%">
<%=salDettaglio.getDataCreazione() != null ? salDettaglio.getDataCreazione() : "" %>
</td>
This retrieve a String from an object and show it into the cell
The problem is the retrieved string represent a date having the following horrible form: 20131204 and I have to convert it into the following form: 2013-12-04.
So I am thinking to create a JavaScript that do this work when the value is retrieved.
My problem is: how can I do to automatically call the JavaScript before to show the value into the td cell? (So I show the modified output in the desidered form)
EDIT 1:
So I have create thid JavaScript function into my page:
function convertData() {
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.innerText = td.innerText.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
}
But it don't work because it never enter in this function (I see it using FireBug JavaScript debugger). Why? What am I missing? Maybe have I to call it explicitly in some way in my td cell?
Of course it is better to fix backend method to make it return proper format. But since you have no control over it try to use something like this:
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
Check the demo below.
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
<table>
<tr>
<td class= "dateToConvert" width = "8.33%">
20131204
</td>
<td class= "dateToConvert" width = "8.33%">
20140408
</td>
</tr>
</table>
I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')
I would like for a user to click an image in this table which is created dynamically based on the JSON data sent from the web service, and have the image change. When clicking the image again it will change back to the first image (inter-changing between only two images).
I have a table being created via jQuery's $.ajax() function which looks like this:
<table border="0" width=80% id="table">
<thead>
<tr>
<td><h3>Check to Renew</h3></td>
<td width=40%><h3>Vendor Part</h3></td>
<td width=100%><h3>Part Description</h3></td>
<td><h3>Unit Price</h3></td>
<td><h3>Quantity</h3></td>
</tr>
</thead>
<tbody>
<tr class="template">
<td><img src="images/checkmark.png" alt="check" id="row1" onclick=""></td>
<td>$vendorPart</td>
<td>$partDescription</td>
<td>$price</td>
<td><input class="quantityClass" name="quantity" value="$quantity"/></td>
</tr>
</tbody>
</table>
Here is the simple Javascript function which changes the images:
renewimg=Array("images/checkmark.png","images/gray_x.png");
function rowImageRefresh(y)
{
document.getElementById(y).src=renewimg[++m];
if (m==1)
{m=-1;}
}
This Javascript function work's beautifully, however only if I pass it the images id (in this case specific to the row). Hard coding for testing purposes proved this. My issue is I would like to be able to create a row id on the fly as the table row is created and then have functionality where that id can be passed.
I guess if I were to illustrate this more it would look something like this:
JavaScript: var row = 1;
HTML:
//table data
<td><img src="images/checkmark.png" alt="check" id="row+[i];i++;" onclick="rowImageRefresh(this.row.id)"></td>
//more table data
Where the id is created dynamically on the fly as each row is created and the onclick function passes the row of the image clicked.
You don't actually need an id at all. For example:
<img src="images/checkmark.png" alt="check" onclick="toggle(this)">
Then the script:
function toggle(element)
{
var sources = ["images/checkmark.png", "images/gray_x.png"],
current = $(element).data('state') || 0;
current = 1 - current;
$(element).data('state', current);
element.src = sources[current];
}
It toggles between the two states, remembering the current state using .data().
You could set individual row id's with id="x". Or, you could just use jQuery to find the index from where the click event occured and get the index of that part.
$('img.check').click(function(){
var id = $(this).index();
rowImageRefresh();
});
Here's one way you might assign an id to each image based on its row index:
$.each(rows, function(index, row) {
var data = $.extend({}, row, { id: "row" + index });
var $row = $(template(data));
$row.removeClass('template');
var $img = $('img', $row);
$img.on('click', function() {
var $this = $(this);
if ($this.data('checked') === true) {
var checked = $this.attr('src');
var unchecked = $this.data('src');
$this.attr('src', unchecked);
$this.data('src', checked);
$this.data('checked', false);
} else {
var unchecked = $this.attr('src');
var checked = $this.data('src');
$this.attr('src', checked);
$this.data('src', unchecked);
$this.data('checked', true);
}
});
$tbody.append($row);
});
The HTML for the image would look like this:
<img src="checked.png" alt="check" data-checked="true" data-src="unchecked.png" id="${ id }" />
Here's a working example: http://jsfiddle.net/potatosalad/MJYpA/1/
I used lodash.js for the template, but whatever you're doing to generate the row HTML should work the same.
Consider using a custom data attribute instead of trying to generate unique ids.
<img src="..." data-partid="$vendorPart" class="part-img" />
$(".part-img").on("click", function() {
var id = $(this).data("partid");
// or
var id = $(this).attr("data-partid").val();
rowImageRefresh(id);
});
Edit:
Seems like you are trying to toggle a checkbox image. A better way might be to change the background image using css and sprites. Then on click you swap the class depending on state.