jQuery select all data from selected rows - javascript

I have a table. I want to get name, lastname, email from all selected rows (check is set). Maybe name, lastname, email will be arrays.
How can I do it?
I've tried this:
var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
var result = [];
$('input:checkbox:checked', tableControl).each(function() {
result.push($(this).parent().next().text());
});
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td id="name_1">Petya</td>
<td id="last_1">L1</td>
<td id="country_1">Country1</td>
<td id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td id="name_2">Kolya</td>
<td id="last_2">L2</td>
<td id="country_2">Country2</td>
<td id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td id="name_3">Vasya</td>
<td id="last_3">L3</td>
<td id="country_3">Country3</td>
<td id="email_3">Email3</td>
</tr>
But I get only selected names. How can I get the other columns?

This is one possible way of doing things . I set a class for every type of column. You can use that to find out all the other information of the checked rows.
Observe the console. you get all the information in one object which you can then use for whatever further functions you might want it to do
var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
var result = [];
$('input:checkbox:checked', tableControl).each(function() {
var obj={};
var parent=$(this).parent().parent();
obj.name=(parent.find( ".name" ).text());
obj.last=(parent.find( ".last" ).text());
obj.country=(parent.find( ".country" ).text());
obj.email=(parent.find( ".email" ).text());
result.push(obj);
});
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td class="name" id="name_1">Petya</td>
<td class="last" id="last_1">L1</td>
<td class="country" id="country_1">Country1</td>
<td class="email" id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td class="name" id="name_2">Kolya</td>
<td class="last" id="last_2">L2</td>
<td class="country" id="country_2">Country2</td>
<td class="email" id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td class="name" id="name_3">Vasya</td>
<td class="last" id="last_3">L3</td>
<td class="country" id="country_3">Country3</td>
<td class="email" id="email_3">Email3</td>
</tr>
<button id="btn">Click</button>

Instead of clicking a button every time you want to sum up your results, i would suggest you handle the result object anytime a checkbox is clicked, this makes for a more stable state and handles dynamic changes better. Consider changing your code to look like:
var tableControl = $('#mytable');
//An object that maps checkbox id to an object containing name, last and email
var result = {};
tableControl.find('input:checkbox').click(function() {
var key = $(this).attr('id');
//If checkbox clicked and not checked, then remove object from map
if(!$(this).is(":checked")){
delete result[key];
return;
}
var row = $(this).parent().parent();
//Get children based on the start of the id string
var firstName = row.children("td[id^='name']").text();
var lastName = row.children("td[id^='last']").text();
var email = row.children("td[id^='email']").text();
result[key] = {
name: firstName,
last : lastName,
email: email
}
});
This way, anytime a checkbox is clicked, the results object will update immediately to reflect the desired value. The result object would look something like this:
{
"check_1": {
"name": "Petya",
"last": "L1",
"email": "Email1"
},
"check_2": {
"name": "Kolya",
"last": "L2",
"email": "Email2"
},
"check_3": {
"name": "Vasya",
"last": "L3",
"email": "Email3"
}
}
https://jsfiddle.net/p35kz2u1/6/

var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
var result = [];
$('input:checkbox:checked', tableControl).each(function() {
// Get the entire text
//alert($(this).closest('tr').children('td').text());
//alert($(this).parent().next().find('td').text());
// Get each column
$(this).closest('tr').children('td').each(function(e){
alert($(this).text());
});
result.push($(this).closest('tr').children('td').text());
});
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td id="name_1">Petya</td>
<td id="last_1">L1</td>
<td id="country_1">Country1</td>
<td id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td id="name_2">Kolya</td>
<td id="last_2">L2</td>
<td id="country_2">Country2</td>
<td id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td id="name_3">Vasya</td>
<td id="last_3">L3</td>
<td id="country_3">Country3</td>
<td id="email_3">Email3</td>
</tr>
<button id="btn">Get Data</button>

var tableControl= $('#mytable');
$("#btn").click(function () {
var result = [];
tableControl('input[type="checkbox"]:checked').each(function() {
var nodeArray = $(this).parents('tr').find('td');
var innerArray = [];
for(var i = 1; i < nodeArray.length; i++) {
if(nodeArray.hasOwnProperty(i)) {
innerArray.push(nodeArray[i].text());
}
}
if(innerArray.length > 0) {
result.push(innerArray);
}
});
alert(result);
});
please try out this, i have not tested, but i think it should do what you want.

You can use something like below. I modified your inner query to go to parent and looks for siblings.
var tableControl = $('#mytable');
$("#btn").click(function() {
var result = [];
$('input:checkbox:checked').each(function(item) {
$(this).parent().siblings().each(function() {
result.push($(this).text())
});
});
alert(result)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" cellpadding="1" border="2">
<thead>
<tr>
<td>Check</td>
<td>Name</td>
<td>Lastname</td>
<td>Country</td>
<td>Email</td>
</tr>
</thead>
<tr>
<td><input id="check_1" type="checkbox" name="check[]"></td>
<td id="name_1">Petya</td>
<td id="last_1">L1</td>
<td id="country_1">Country1</td>
<td id="email_1">Email1</td>
</tr>
<tr>
<td><input id="check_2" type="checkbox" name="check[]"></td>
<td id="name_2">Kolya</td>
<td id="last_2">L2</td>
<td id="country_2">Country2</td>
<td id="email_2">Email2</td>
</tr>
<tr>
<td><input id="check_3" type="checkbox" name="check[]"></td>
<td id="name_3">Vasya</td>
<td id="last_3">L3</td>
<td id="country_3">Country3</td>
<td id="email_3">Email3</td>
</tr>
</table>
<button id ="btn">Click Me</button>

Related

How do I sum all columns in a table with the same classname in JavaScript?

I am trying to sum a price in a table, all the prices in the <td> have the same class name and I'd like to sum them up on a button click. I would eventually like to calculate the quantity into the total as well. This is what I have so far:
function sumAmounts() {
var sum = 0;
var listPriceTotal = $('.txtListPrice').each(function() {
sum += parseFloat($(this).html); // Or this.innerHTML, this.innerText
});
document.getElementById("txtTotal").value = listPriceTotal;
}
document.getElementById("addTotals").addEventListener("click", () => {
sumAmounts();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th><label>SKU</label></th>
<th><label>Retail Price</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td class="txtSKU">1234</td>
<td class="txtRetailPrice">12.50</td>
<td class="txtListPrice">11.75</td>
<td class="txtProductName">product 1</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tr>
<td class="txtSKU">12222</td>
<td class="txtRetailPrice">14.50</td>
<td class="txtListPrice">9.75</td>
<td class="txtProductName">product 2</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tfoot>
<th><label id="lblTotal">Total:</label><input type="text" name="txtTotal" id="txtTotal">
<input type="button" value="Add" id="addTotals">
</th>
</tfoot>
</table>
There's two issues in your code. Firstly you're trying to set a jQuery object as the value of the input, which is why you see [Object object] in the field. You need to set the value to sum.
The second issue is that you're supplying the html method reference to parseFloat(), not the actual html() value. With both of those addressed, the code works:
function sumAmounts() {
var sum = 0;
$('.txtListPrice').each(function() {
sum += parseFloat($(this).html());
});
document.getElementById("txtTotal").value = sum;
}
document.getElementById("addTotals").addEventListener("click", () => {
sumAmounts();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th><label>SKU</label></th>
<th><label>Retail Price</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td class="txtSKU">1234</td>
<td class="txtRetailPrice">12.50</td>
<td class="txtListPrice">11.75</td>
<td class="txtProductName">product 1</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tr>
<td class="txtSKU">12222</td>
<td class="txtRetailPrice">14.50</td>
<td class="txtListPrice">9.75</td>
<td class="txtProductName">product 2</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tfoot>
<th>
<label id="lblTotal">Total:</label>
<input type="text" name="txtTotal" id="txtTotal">
<input type="button" value="Add" id="addTotals">
</th>
</tfoot>
</table>

how can i get table of values exist in a TD of a table use jquery?

i want when i check checkbox in table get array values check (NAME, FIRST NAME, SALAIRENET) in example below it gives me just SALAIRENET and give NaN a name for the line check, please help me.
he is my table
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $salarie->matricule }}</td>
<td class="name">{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td class="salaireValue">{{ $salarie->salairenet }}</td>
<td><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
he is my code jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var currentHtml = $(allChecked[i]).parent().siblings('.salaireValue')[0];
var currentHtml1 = $(allChecked[i]).parent().siblings('.name')[0];
var result = parseInt($(currentHtml)[0].innerText);
var result1 = parseInt($(currentHtml1)[0].innerText);
console.log(result);
console.log(result1);
}
});
});
</script>
It might be helpful to create functions to break up the work. Also you can use parseInt() but it must receive a String that represents an Integer, so "1000" versus "One Thousand".
Consider the following:
$(function() {
function checkToggleAll(c, v) {
$(".checkbox", c).each(function(i, el) {
$(el).prop("checked", v);
});
}
function checkAll(c) {
if ($(".checkbox:checked", c).length == $(".checkbox", c).length) {
$("#check_all").prop("checked", true);
} else {
$("#check_all").prop("checked", false);
}
}
function gatherData(c) {
var rows = {}
$(".checkbox:checked", c).each(function(i, el) {
var row = $(el).parent().parent();
rows[row.attr("id")] = {
Name: $(".first-name", row).text().trim(),
SurName: $(".sur-name", row).text().trim(),
SalaireValue: parseInt($(".salaireValue", row).text().trim())
};
});
return rows;
}
$("#check_all").change(function() {
checkToggleAll($("tbody"), $(this).prop("checked"));
console.log(gatherData($(".table tbody")));
});
$("tbody .checkbox").on("change", function() {
checkAll($(".table tbody"));
console.log(gatherData($(".table tbody")));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<thead>
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
</thead>
<tbody>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1001</td>
<td class="name">Simpson, Homer</td>
<td class="salaireValue">60000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>1002</td>
<td class="name">Leonard, Lenny</td>
<td class="salaireValue">40000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_3">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="3"></td>
<td>3</td>
<td>1002</td>
<td class="name">Carlson, Carl</td>
<td class="salaireValue">55000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</tbody>
</table>
I assume that the table content might get updated dynamically, so I am using .on() just in case. You can use .change() if needed.
Hope that helps.
A few changes in your for loop will make it:
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
I've also separated the names into two spans in order to make it easy to select them.
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">123</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>2</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">456</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</table>

How to pass the selected checkbox rows to a function

I have to pass the selected rows to a function( ). From the below code, I am able to get the value of selected checkbox but could not get the entire row. Please help me on how to get the entire selected rows and pass those rows to a function.
my html code:
<div id ="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank" >100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1" >100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2" >100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>
My jQuery Code:
$('#div_table').click(function() {
var result = []
$('input:checkbox:checked', tableControl).each(function() {
result.push($(this).parent().next().text());
});
alert(result);
});
The selected rows should be passed to the below function:I have to use these rows one by one and store.
function invokeAllEligibleSaves(result){
alert(result)
}
It will be very much useful for me If i get a working code. Thanks in advance.
One way to achieve that is like this:
First : get a reference to the input element that triggered the function. From this element, you can reach the .closest() parent that has the tag <tr>.
Second: This can then be queried for all of its <td> .children() and each child will either have .text() or .html() to report back. I think in your case, you are interested in the text part.
Third: You will need to push all .text() values in a separate array, that will be your row. Then push that row into another array result. So your result will be an array of arrays.
$('#div_table').click(function() {
var result = [] // create an empty array for all rows
$('input:checkbox:checked').each(function() {
var row = []; // create an empty array for the current row
//loop through all <td> elements in that row
$(this).closest('tr').children('td').each(function(){
// add .text() or .html() if you like
row.push($(this).text());
});
// now push that row to the result array
result.push(row);
});
alert(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank">100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1">100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2">100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>
You just need an additional .parent() in your result.push statement to get the whole row, because you're only getting the cell so far:
result.push($(this).parent().parent().next().text());
This would be a more effective solution for your problem. The drawback with the accepted answer is, it will get triggered whenever & wherever you click inside the table (even when you click on a text).
Here it gets updated only when a checkbox is selected.
$(document).ready(function() {
$('input:checkbox').on('change', function() {
var result = [];
$('input:checkbox:checked').each(function() {
var rowText = '';
$(this).parent().siblings().each(function() {
rowText += $(this).text() + ' ';
});
result.push(rowText.trim());
});
alert(JSON.stringify(result));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id ="div_table">
<table id="myTable">
<tr>
<th>SELECT</th>
<th>BANKID</th>
<th>EFFECTIVE SAVE DATE</th>
<th>SAVE MONTH</th>
<th>MONTH OF SUBMISSION</th>
<th>PILLAR</th>
<th>LEVER</th>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1000" id="1000"></td>
<td id="bank" >100000</td>
<td id="edate">10-02-2009</td>
<td id="month">Jan</td>
<td id="subMonth"><input type="text" id="subMonth"></td>
<td id="pillar"><input type="text" id="pillar1"></td>
<td id="lever"><input type="text" id="lever1"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1001" id="1001"></td>
<td id="bank1" >100001</td>
<td id="edate1">12-12-2010</td>
<td id="month1">Feb</td>
<td id="subMonth1"><input type="text" id="subMonth2"></td>
<td id="pillar1"><input type="text" id="pillar2"></td>
<td id="lever1"><input type="text" id="lever12"></td>
</tr>
<tr>
<td><input type='checkbox' name='chck' value="1002" id="1002"></td>
<td id="bank2" >100002</td>
<td id="edate2">18-02-2018</td>
<td id="month2">Apr</td>
<td id="subMonth2"><input type="text" id="subMonth3"></td>
<td id="pillar2"><input type="text" id="pillar3"></td>
<td id="lever2"><input type="text" id="lever13"></td>
</tr>
</table>
</div>

Why is my javascript not looping

I have the following code which works fine for the first row, but doesn't seem to loop through the table
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="2" id="demotbl">
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
</tr>
<tr>
<td id="prodref">AA1</td>
<td><input type="text" name="h_prodref" id="h_prodref"></td>
</tr>
<tr>
<td id="prodref">BB1</td>
<td><input type="text" name="h_prodref" id="h_prodref"></td>
</tr>
<tr>
<td id="prodref">CC1</td>
<td><input type="text" name="h_prodref" id="h_prodref"></td>
</tr>
<tr>
<td id="prodref">DD1</td>
<td><input type="text" name="h_prodref" id="h_prodref"></td>
</tr>
<tr>
<td id="prodref">EE1</td>
<td><input type="text" name="h_prodref" id="h_prodre5"></td>
</tr>
<tr>
<td id="prodref">FF1</td>
<td><input type="text" name="h_prodref" id="h_prodref"></td>
</tr>
</table>
<p id="demo"></p>
<script type="text/javascript">
var x = document.getElementById("demotbl").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr elements in the table.";
var prodref = document.getElementById("prodref").innerHTML;
var i = 0;
do {
document.getElementById("h_prodref").value = prodref;
i++;
}
while (i < x);
</script>
</body>
</html>
My understanding (which is very basic) is that the code will look for a id called prodref and then copy the cell value to the text box, and work its way down until it has completed all rows.
As mention above id must be unique. I create the following example using classes instead:
var x = document.getElementById("demotbl").rows.length;;
document.getElementById("demo").innerHTML = "Found " + x + " tr elements in the table.";
var prodref = document.getElementsByClassName("prodref");
var h_prodref = document.getElementsByClassName("h_prodref");
var i = 0;
for (i; i < prodref.length; i++) {
h_prodref[i].value = prodref[i].innerHTML;
}
<table width="100%" border="0" cellspacing="2" cellpadding="2" id="demotbl">
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
</tr>
<tr>
<td class="prodref">AA1</td>
<td>
<input type="text" name="h_prodref" class="h_prodref">
</td>
</tr>
<tr>
<td class="prodref">BB1</td>
<td>
<input type="text" name="h_prodref" class="h_prodref">
</td>
</tr>
<tr>
<td class="prodref">CC1</td>
<td>
<input type="text" name="h_prodref" class="h_prodref">
</td>
</tr>
<tr>
<td class="prodref">DD1</td>
<td>
<input type="text" name="h_prodref" class="h_prodref">
</td>
</tr>
<tr>
<td class="prodref">EE1</td>
<td>
<input type="text" name="h_prodref" class="h_prodref">
</td>
</tr>
<tr>
<td class="prodref">FF1</td>
<td>
<input type="text" name="h_prodref" class="h_prodref">
</td>
</tr>
</table>
<p id="demo"></p>
Example with your original html that I don't suggest using Document.querySelectorAll():
var x = document.getElementById("demotbl").rows.length;;
document.getElementById("demo").innerHTML = "Found " + x + " tr elements in the table.";
var prodref = document.querySelectorAll("#prodref");
var h_prodref = document.querySelectorAll("#h_prodref");
var i = 0;
for (i; i < prodref.length; i++) {
h_prodref[i].value = prodref[i].innerHTML;
}
<table width="100%" border="0" cellspacing="2" cellpadding="2" id="demotbl">
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
</tr>
<tr>
<td id="prodref">AA1</td>
<td>
<input type="text" name="h_prodref" id="h_prodref">
</td>
</tr>
<tr>
<td id="prodref">BB1</td>
<td>
<input type="text" name="h_prodref" id="h_prodref">
</td>
</tr>
<tr>
<td id="prodref">CC1</td>
<td>
<input type="text" name="h_prodref" id="h_prodref">
</td>
</tr>
<tr>
<td id="prodref">DD1</td>
<td>
<input type="text" name="h_prodref" id="h_prodref">
</td>
</tr>
<tr>
<td id="prodref">EE1</td>
<td>
<input type="text" name="h_prodref" id="h_prodref">
</td>
</tr>
<tr>
<td id="prodref">FF1</td>
<td>
<input type="text" name="h_prodref" id="h_prodref">
</td>
</tr>
</table>
<p id="demo"></p>
Also you have a typo here:
<tr>
<td id="prodref">EE1</td>
<td><input type="text" name="h_prodref" id="h_prodre5"></td>
</tr>
id is h_prodref no h_prodre5.
Here you go.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<table width="100%" border="0" cellspacing="2" cellpadding="2" id="demotbl">
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
</tr>
<tr>
<td id="prodref1">AA1</td>
<td><input type="text" name="h_prodref" id="h_prodref1"></td>
</tr>
<tr>
<td id="prodref2">BB1</td>
<td><input type="text" name="h_prodref" id="h_prodref2"></td>
</tr>
<tr>
<td id="prodref3">CC1</td>
<td><input type="text" name="h_prodref" id="h_prodref3"></td>
</tr>
<tr>
<td id="prodref4">DD1</td>
<td><input type="text" name="h_prodref" id="h_prodref4"></td>
</tr>
<tr>
<td id="prodref5">EE1</td>
<td><input type="text" name="h_prodref" id="h_prodref5"></td>
</tr>
<tr>
<td id="prodref6">FF1</td>
<td><input type="text" name="h_prodref" id="h_prodref6"></td>
</tr>
</table>
<p id="demo"></p>
<script type="text/javascript">
var x = document.getElementById("demotbl").rows.length - 1;
document.getElementById("demo").innerHTML = "Found " + x + " tr elements in the table.";
var i = 0;
do {
var prodref = document.getElementById("prodref" + (i + 1)).innerHTML;
document.getElementById("h_prodref" + (i + 1)).value = prodref;
i++;
}
while (i < x);
</script>
</body>
</html>
I not sure that this will be the solution to your problem. I have done something similar in the past. My tip is not to use 'id' when dealing with more than one element but to use 'class' instead. Hope you fix it! :)
You have many elements with the same id. id is always unique to a element. If you are using id's as a way to say apply the same styles to multiple elements you should use a class instead.
In your code the statement:
document.getElementById("prodref")
will always return you the first element matching the id: "prodref". Which is the element:
<td id="prodref">AA1</td>
.getElementById() returns the same element so you are setting the same td in every loop. This will do what you wanted;
var i = 0;
var elements = document.getElementsByTagName("td");
do {
elements[i+1].firstChild.value = elements[i].innerText;
i = i+2;
}
while (i < elements.length);

jQuery problems with parent().remove()

I am trying to clone and remove a table with jQuery, without success.
Here is an example, the table I want to operate:
<table>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
<tr>
<td colspan="3">Dummy1</td>
<td colspan="3">Dummy2</td>
</tr>
<tr>
<td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
<td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
<td colspan="2"><img src="./images/add.gif" /><img src="./images/delete.gif" /></td>
</tr>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
</table>
Now, the javascript functions add() and remove():
function add(o){
var o = $(o);
var tr = o.parent().parent().parent();
tr.after(tr.clone());
tr.find('.adicionar').remove();
tr.find('.remover').show();
tr.next().find('input, select').val('');
tr.next().find('.remover').hide();
}
function remove(o){
var o = $(o);
o.parent().parent().parent().remove();
}
add(this) works perfectly, but the remove(this) is not working, it removes just my "delete.gif" image. What am I doing wrong please?
Look at the jsFiddle.
I used jQuery for what you need.
<table>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
<tr>
<td colspan="3">Dummy1</td>
<td colspan="3">Dummy2</td>
</tr>
<tr>
<td colspan="2"><input name="aperf_cursos[]" type="text" /></td>
<td colspan="2"><input name="aperf_entidades[]" type="text" /></td>
<td colspan="2">AddDelete</td>
</tr>
<tr>
<td colspan="6" class="linha_space"></td>
</tr>
</table>
$(function() {
$(document).on('click', '.adicionar', function(event){
var o = $(event.target);
var tr = o.closest('table');
tr.after(tr.clone());
tr.find('.adicionar').remove();
tr.find('.remover').show();
tr.next().find('input, select').val('');
tr.next().find('.remover').hide();
});
$(document).on('click', '.remover', function(event){
var o = $(event.target);
var table = $(o.closest('table'));
table.remove();
});
});
Instead of this parent.parent.parent madness (it's madness, yes it is) why don't you use
element.closest("tr")
to find the row it's in?
This approach will work consistently.

Categories

Resources