I have a JavaScript function that is not working as I expected. The function should loop through the input boxes and display an alert with the input's value. For some reason, the inputs are all returning an undefined. I am sure the ids of the input elements are correct. I can perform other actions on the input (change color, set .innerHTML), but I can't seem to collect the values. Can someone point out what I may be doing wrong?
function submitHours(){
var table = document.getElementById('StudentList');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName("tr");
for (var r = 1; r < rows.length+1; r++) {
for(x=1; x<=25; x++){
document.getElementById(r+'day'+x).style.backgroundColor = 'red';
alert(document.getElementById(r+'day'+x).value);
}
}
}
It looks like you're selecting an element that contains the input you're targeting, but not the input itself. This is why you can set the .innerHTML, but not get the .value.
To get the value, do this:
function submitHours(){
var rows = document.querySelector('#StudentList > tbody:first-child > tr');
for (var r = 1; r < rows.length+1; r++) {
for(var x=1; x<=25; x++){
var input = document.querySelector('#' + r+'day'+x + " input");
input.style.backgroundColor = 'red';
alert(input.value);
}
}
}
There's probably a more efficient way to do this, but I can't tell without seeing your markup.
You need to use innerText instead of value:
for(x=1; x<=25; x++){
document.getElementById(r+'day'+x).style.backgroundColor = 'red';
alert(document.getElementById(r+'day'+x).innerText);
}
Related
I'm trying to change those cells background colour that innerHTML values match with my array. How can i make it?
var numbers = ["15628","15623","15656","11628"];
var table = document.querySelector("[name='main']")
.contentWindow.document.getElementById("music").rows.length;
for (i = 4; i < table -1; i++){
if (document.querySelector("[name='main']")
.contentWindow.document.getElementById("music").rows[i].cells[1].innerHTML == numbers)
{
document.querySelector("[name='main']")
.contentWindow.document.getElementById("music")
.rows[i].cells[1].style.backgroundColor = "yellow";
};
Are you sure this element select is correct: document.querySelector("[name='main']").contentWindow.document.getElementById("music").rows[i].cells[1] ?
It hard analize without looking to html.
If it OK, maybe you need such solution:
for (i = 4; i < table -1; i++){
let value = document.querySelector("[name='main']")
.contentWindow.document.getElementById("music").rows[i].cells[1].innerHTML;
if (numbers.includes(value))
{
document.querySelector("[name='main']")
.contentWindow.document.getElementById("music")
.rows[i].cells[1].style.backgroundColor = "yellow";
};
I draw a table (through datatable) and I would need to retrieve some specific data depending on certain conditions.
here is the table:
tom
dsdsdsds
oo
60
jones
aa
oo
61
I need to parse each tr elements, and if the td input type checkbox contains the class selected, I need to retrieve the value of td with id="id" (of the same tr).
I tried to do the following:
var nbr_lignes = document.getElementById('datatable-table').rows.length;
var i = 0;
var j = 0;
while(i < nbr_lignes){
j=0;
console.log("ligne: "+i);
var nbr_colonnes = document.getElementById('datatable-table').getElementsByTagName('tr')[i].getElementsByTagName('td').length;
console.log("nb colonnes: "+nbr_colonnes);
while(j < nbr_colonnes){
console.log("contenu td: "+document.getElementById('datatable-table').getElementsByTagName('tr')[i].getElementsByTagName('td')[j].
innerHTML);
j++;
}
i++;
}
so I can parse each td of each tr but I don't know how to check if the current td contains the class selected and in that case retrieve the value of the td id="id"
I would appreciate if you can help me.
Here is a simple solution: you're making a counter and iteration through every line ( tr ), whenever you find input.selected inside it, you are asking for value of the div with id of a counter. The result is stored in found table.
https://jsfiddle.net/prowseed/80rmcjgu/19/
var idx = 1;
var found = [];
var trs = [].slice.call(document.querySelectorAll('table tr'));
trs.forEach(function(tr){
var isSelected = (tr.querySelector('input')).classList.contains('selected');
console.log(isSelected);
if(isSelected){
console.log(document.getElementById('id'+idx));
var value = (document.getElementById('id'+idx)).innerText;
found.push({id: idx, value: value});
}
idx++;
});
(document.getElementById('result')).innerHTML = found.reduce(function(p, c){ return p + ' \n ' + c.id + ':' + c.value }, '');
I'm very new to programming, especially to JavaScript and I encounter some problem with putting some values from an array to td elements.
I want to grab the nodeValue from td Elements performe some calculation on it and put it back in some other td-elements. The first part works fine, but I didn't get it right to put the values back from the array in other td elements.
I always get the warning in the console.:
TypeError:
document.getElementById(...).getElementsByTagName(...).item(...) is
null
What do I wrong? The relevant code:
for (i = 0; i <= getPreis.length; i++) {
priceNumber += 1;
newElement += 1;
}
function myFunction() {
// create array element
var oldPrice = [];
// get all td elements in id "originalPrice"
var getPreis = document.getElementById('originalPrice').getElementsByTagName('td');
// determine number of td elements
for (i = 0; i < getPreis.length; i++) {
oldPrice.push(getPreis[i].childNodes[0].nodeValue);
}
// get all td elements in id "listNewPrice"
var putPreis = document.getElementById('listNewPrice').getElementsByTagName('td');
// set index of item
var newElement = 0;
// set index for array
var priceNumber = 0;
// perform operation on array element
var newPrice = oldPrice[priceNumber] * 0.94;
/* it got problems with this for loop
here i want to loop through all td elements in tr "listNewPrice" and put the values from the array in there */
for (i = 0; i <= getPreis.length; i++) {
priceNumber += 1;
newElement += 1;
}
document.getElementById("listNewPrice").getElementsByTagName('td').item(newElement).innerHTML = newPrice;
}
<!DOCTYPE html>
<html>
<body>
<table>
<tbody>
<tr id="originalPrice">
<td>22.50</td>
<td>45.00</td>
<td>75.00</td>
</tr>
<tr id="listNewPrice">
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button onclick="myFunction()">Click me</button>
</body>
</html>
You need to move the calculation and assignment of the result to the td element inside your loop as you are using incrementing index values that get calculated inside the for loop.
for (i = 0; i < getPreis.length; i++) {
var newPrice = oldPrice[priceNumber] * 0.94;
document.getElementById("listNewPrice").getElementsByTagName('td').item(newElement).innerHTML = newPrice;
priceNumber += 1;
newElement += 1;
}
In your example newElement === 2 after the for loop then you try and get the item at index 2 of the array of td elements which doesn't exist. Hence the error
document.getElementById(...).getElementsByTagName(...).item(...) is null
Example JSFiddle
Since you are going to be reading numeric data out of the original table and performing calculations on it, you'll need to ensure that you are properly parsing the values as numbers instead of strings.
You can do this by using the parseFloat() function when reading in your values :
for (i = 0; i < getPreis.length; i++) {
// Read in the actual values (so they will be usable in calculations)
oldPrice.push(parseFloat(getPreis[i].childNodes[0].nodeValue));
}
Then when updating your values, just perform the operation backwards (i.e. iterate through your loop and set the values of each node) :
// determine number of td elements
for (i = 0; i < getPreis.length; i++) {
putPreis[i].innerHTML = oldPrice[i] * 0.94;
}
Both of these changes will allow you to greatly simplify your existing code :
function myFunction() {
// create array element
var oldPrice = [];
// get all td elements in id "originalPrice"
var getPreis = document.getElementById('originalPrice').getElementsByTagName('td');
// determine number of td elements
for (i = 0; i < getPreis.length; i++) {
oldPrice.push(parseFloat(getPreis[i].childNodes[0].nodeValue));
}
// get all td elements in id "listNewPrice"
var putPreis = document.getElementById('listNewPrice').getElementsByTagName('td');
// update your values
for (i = 0; i < getPreis.length; i++) {
putPreis[i].innerHTML = oldPrice[i] * 0.94;
}
}
Example
You can see a working example of this here and demonstrated below :
here is the deal, i have the following jquery code that should add the array values to specific #id, buf it does not replace the code, only add more, and i need a little help to make it replace the html on othe link click.
Code:
function changeClass(curClass){
switch(curClass){
case "Schoolgirl":
case "Fighter":
var charSkillsNames = ["text1","text2","text4","text5"];
//loop show array values
listSkillsNames(charSkillsNames);
break;
}
}
function listSkillsNames(arr){
var length = arr.length,
element = null;
$("#skills").html(function(){
for (var i = 0; i < length; i++) {
element = arr[i];
$(this).append("<li>"+element+"</li>");
}
});
}
this works well but i need it to replace the html inside the "#skills" id when i click on the link that makes it work
PS: problem is really here
The issue is that you don't empty the HTML of #skills element. Use $("#skills").html("") to empty it.
function listSkillsNames(arr){
var length = arr.length,
element = null;
var $skills = $("#skills");
$skills.html(""); // empty the HTML
for (var i = 0; i < length; i++) {
element = arr[i];
$skills.append("<li>"+element+"</li>"); // append new items
}
}
The problem is because you are keep appending new items to the element always without removing the existing items.
Just empty the skill element, also there is no need to use the .html(function(){}) here
function listSkillsNames(arr) {
var length = arr.length,
element = null;
var $skill = $("#skills").empty();
for (var i = 0; i < length; i++) {
element = arr[i];
$skill.append("<li>" + element + "</li>");
}
}
I have an array called tmp
var tmp = ["05", "13", "27"];
if an option value is equal to a value within tmp, I want to add that option to a particular optgroup, else add it to the other optgroup. I keep getting everything added to optgroup #2, except the option with the value "27". What am I doing incorrectly?
var groups = $("optgroup");
$("option").each(function() {
var value = $(this).val();
for (var x = 0; x < tmp.length; x++) {
var isMatch = (tmp[x] === value);
if (isMatch) {
$(this).appendTo($(groups[0]));
} else if (value.length > 0) {
$(this).appendTo($(groups[1]));
}
}
});
Thanks for any pointers to correct this.
~ck in San Diego
You should add a break after each appendTo statement so that you don't keep comparing the option to all tmp values.
var groups = $("optgroup");
$("option").each(function() {
var value = $(this).val();
for (var x = 0; x < tmp.length; x++) {
var isMatch = (tmp[x] === value);
if (isMatch) {
$(this).appendTo($(groups[0]));
break;
} else if (value.length > 0) {
$(this).appendTo($(groups[1]));
break;
}
}
});
Firstly,
$(this).appendTo($(groups[1]));
can be changed to
$(this).appendTo(groups[1]);
you don't need to wrap the element again into a jQuery object in order to append to it, a HTMLElement will work fine.
Do you have the HTML that you're using and where are your <option> elements that you are checking the value of?
EDIT:
I've rewritten your code slightly and this works correctly (N.B. appending won't work in IE6 and I believe 7 and 8 too - In IE the innerHTML property for a select element is readonly, so use createElement or the Option constructor to create options),
Working Example. add /edit to the URL to see the code. I have the option elements in an array in the working example, I assume that you have them in a similar structure.
var groups = $("optgroup");
$('options').each(function() {
var $this = $(this);
var val = $this.val();
if (tmp.indexOf(val) !== -1) {
$this.appendTo(groups[0]);
}
else if (val.length > 0) {
$this.appendTo(groups[1]);
}
});