Get the selected rows from a table - javascript

I have a table that has 10 rows and 3 columns and each row has a checkbox associated with it. The user can select any number of rows and when he presses the Submit button an alert message needs to be displayed containing the values in all the selected rows preferably as a JSON string. How do I extract all the selected rows alone and convert it to a JSON string using either Javascript or Jquery?

I hope I've understood your requirements well. Please consider this solution.
$('#btn-table-rows').click(function (event) {
var values = [];
$('table #row-selector:checked').each(function () {
var rowValue = $(this).closest('tr').find('td.row-value').text();
values.push(rowValue)
});
var json = JSON.stringify(values);
alert(json);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>
<input id="row-selector" type="checkbox"/>
</td>
<td class="row-value">Row #1: Hello</td>
</tr>
<tr>
<td>
<input id="row-selector" type="checkbox"/>
</td>
<td class="row-value">Row #2: World</td>
</tr>
</table>
<button id="btn-table-rows">Process</button>

Related

how to search for a checkbox inside innerHTML?

I want to sum a selected column inside a table. 2nd and 3rd column in my case. I managed to get the sum but I really want to add the value of a row in case a checkbox in column #1 is checked.
I can get the innerHTML value of a cell abut I do not know how to search or find out if the checkbox inside is checked or not.
console.log(cell.innerHTML);
returns for example
"Extend (2x)<input type=\"checkbox\" id=\"Extend2x\" name=\"Extend2x\" class=\"beru\" <=\"\" td=\"\">
so I can see that the checkbox is there but that is where I ended up
I tried
console.log(cell.innerHTML.getElementsByTagName("checkbox"));
console.log(cell.innerHTML.html());
console.log(cell.html());
console.log($(cell).find(':checkbox').checked) returns undefined
but nothing worked.
Could somoone help me to find out? The working fiddle is here You just click the checkbox and summing of the columns will be done.
The code you are looking for is this
$(':checked')
you can add stuff like input:checked, or something to make it more specific.
EDIT--
just saw the comments - and Taplar already answered this. Well this can be considered as alternative answer, and does not need to use cells / iterate through cells of the table.
I think this is what you wanted. This is using jQuery for every reference to elements in the the dom (html).
$(".beru").on('change', function() {
updateTotals();
});
function updateTotals() {
// loop cells with class 'celkem'
$('.celkem').each(function(){
// for each celkem, get the column
const column = $(this).index();
let total = 0;
// loop trough all table rows, except the header and the row of totals
$(this).closest('table').find('tr:not(:first, :last)').each(function(){
if($(this).find('input').is(':checked')) {
// if the input is checked, add the numeric part to the total
const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
if(str) {
total += Number(str);
}
}
});
if(!total) {
// if the total is zero, clear the cell
$(this).text("");
} else {
// otherwise, print the total for this column in the cell
$(this).text(total + " EUR");
}
});
}
td {
width: 25%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox" id="Extend2x" name="Extend2x" class="beru"</td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox" id="Zinobiotic" name="Zinobiotic" class="beru"</td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
If you already have a reference to the DOM element then just select all the checkboxes using a selector.
var cbList = cell.querySelectorAll("[type='checkbox']");
for(var i = 0; i < cbList.length; i++){
//do something with each checkbox
//cbList[i];
}
Remember a node list is not an array, so you can't use forEach ;)

Show rows in table with cells name attribute containing string from input (JQuery)

I would like to have keyup function that would show only rows matching the input text by cell that spans on multiple rows.
Consider following table:
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1'> dummy1 </td>
</tr>
<tr>
<td name='Key1'> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2'> dummy3 </td>
</tr>
<tr>
<td name='Key2'> dummy4 </td>
</tr>
</table>
jsfiddle
Here each row has second td tag with name that matches its "parent" column text. So when I type 'Key1' at the input field I would like it to show only dummy1 and dummy2. Is it possible in jquery?
I understand that you want to display the rows that has a matching name. If this is wrong, please elaborate more, then I can update it.
Here is a demo: https://jsfiddle.net/erkaner/gugy7r1o/33/
$('input').keyup(function(){
$('tr').hide();
$("td").filter(function() {
return $(this).text().toLowerCase().indexOf(keyword) != -1; }).parent().show().next().show();
});
});
Here's my take on your issue, assuming you always want the first column to show. https://jsfiddle.net/gugy7r1o/2/
<input type="text" id="myInput" />
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1' class="data"> dummy1 </td>
</tr>
<tr>
<td name='Key1' class="data"> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2' class="data"> dummy3 </td>
</tr>
<tr>
<td name='Key2' class="data"> dummy4 </td>
</tr>
</table>
.data{
display:none;
}
var theData = $('td.data');
var input = $('#myInput').on('keyup', function(){
theData.hide();
var value = input.val();
var matches = theData.filter('[name="'+value+'"]');
matches.show();
});
Firstly, I would recommend using <ul> to wrap each key in as tables should be used for data structure (Forgive me if that is what it is being used for).
Secondly, just attach an on keyup event to the search box and then find matches based on the id. See example below:
JS Fiddle Demo
It is also worth mentioning that it could be useful attaching a timeout to the keyup event if you end up having large amounts of rows so that only one filter is fired for fast typers!

Iterating through table and get the value of a button in each tablerow jQuery

I have buttons in a table which are created dynamically. I want to iterate through a table, get the tablerows which contain a checked checkbox and get the value of a button inside the tablerow. I want to push the values in an array after. The buttons don't have a unique ID so I cannot get their values by id.
I tried to get the values through giving the buttons a class and itering works fine but the array is filled with empty entries.
$("#bt_multiple_deletion").off().on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).find(".filefolder-button").text());
});
})
I really don't know what Im doing wrong. I tried to get the values with .text(), .val() etc.
My table row looks like this:
<tr class="select">
<td>
<span class="countEntries"><input id="lv_fifo_ctrl7_cb_delete_file" type="checkbox" name="lv_fifo$ctrl7$cb_delete_file" /></span>
</td>
<td>
<img src="images/icons/013_document_02_rgb.png" alt="document" />
</td>
<td class="name">//the button i want to get the value from
<input type="submit" name="lv_fifo$ctrl7$bt_file" value="013_document_png.zip" id="lv_fifo_ctrl7_bt_file" class="filefolder-button download file del" style="vertical-align: central" />
</td>
<td>
<span id="lv_fifo_ctrl7_lb_length">33.14 KB</span>
</td>
<td>
<span id="lv_fifo_ctrl7_lb_CreationTime">21.10.2014 07:34:46</span>
</td>
<td></td>
<td>
<input type="submit" name="lv_fifo$ctrl7$bt_del_file" value="delete" id="lv_fifo_ctrl7_bt_del_file" class="delete-button delete-file" />
</td>
</tr>
The problem is rows is the input elements not the tr elements so in the loop you need to find the tr which contains the input then find the target element inside it
$("#bt_multiple_deletion").off().on("click", function () {
var checked = $(".select").find("input[type=checkbox]:checked");
var files = checked.map(function () {
return $(this).closest('tr').find(".filefolder-button").val();
}).get();
})
Another option is
$("#bt_multiple_deletion").off().on("click", function () {
var rows = $(".select").find("tr").has('input[type=checkbox]:checked');
//var rows = $(".select").find('input[type=checkbox]:checked').closest('tr');
var files = rows.map(function () {
return $(this).find(".filefolder-button").val();
}).get();
})
#Timo Jokinen Do you need this
$("#bt_multiple_deletion").on("click", function () {
var files = [];
var rows = $(".select").find("input[type=checkbox]:checked");
rows.each(function () {
files.push($(this).parents("tr").find("td.filefolder-button").text());
});
console.log(files);
})
<table class="select">
<tr>
<td class="filefolder-button">test1</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test2</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td class="filefolder-button">test3</td>
<td><input type="checkbox" /></td>
</tr>
</table>
<button id="bt_multiple_deletion">delete</button>
Checkout example link here

Getting wrong tr id with .closest .attr

I am reading tables tr id with closest attribute on change but I keep getting wrong values and do not know how to fix.
If I choose the firts the "lower"(16) checkbox, I get the tr id ok and after that the upper one everythins peachy. Now if I do it the other way around I keep only getting the value of the "top"(17) one. My guess is that it is because the class name is the same, but I´m not sure and I can not influence the class name, since it is generated by Datatables.
Could someone take a peek at jquery and tell me what I´m doing wrong.
Thank you for your help.
var a = $(".report_report").change(function() {
var closestTr = $('.report_report:checkbox:checked').closest('tr').attr('id');
alert(closestTr);
This the basic table concept
<table class="something">
<tr id = "17">
<td>
<input class="report_report" type = "checkbox">
</td>
</tr>
<tr id = "16">
<td>
<input class="report_report" type = "checkbox">
</td>
</tr>
</table>
try
HTML
<table class="something">
<tr id="17">
<td>
<input class="report_report" type="checkbox"/>
</td>
</tr>
<tr id="16">
<td>
<input class="report_report" type="checkbox"/>
</td>
</tr>
</table>
JS
$(".report_report").change(function() {
alert($(this).closest("tr").attr("id"));
});
DEMO
IF you want all selected check box with parent tr id
$(".report_report").change(function () {
var cheked = $(".report_report").filter(function () {
return this.checked;
}).closest("tr").get();
console.log(cheked);
});
NOTE: you html is invalid tr is not closed

Javascript: Parsing html table

I am working on a html page. The page has a table with 3 columns and a button. One of the columns of the table is a check box (The number of rows are changed dynamically):
<table cellpadding="0" cellspacing="0" border="1" class="display" id="tag" width="100%">
<tbody>
<tr>
<td align="center">
<input type="checkbox" class="case" name="case" value="0"/>
<td>fruit</td>
<td>apple</td>
</tr>
<tr>
<td align="center">
<input type="checkbox" class="case" name="case" value="1"/>
<td>fruit</td>
<td>pear</td>
</tr>
</tbody>
</table>
<p><input type="button" value="Generate" onclick="generate()"></p>
When user click the "Generate" button, the generate() function will generate a special string base on the column of each row.
My question is that how can I check if the "checkbox" row is checked or not? I would like to filter those non-checked rows when I generate the string.
Thanks.
Filter the rows based upon which have a checked checkbox:
var rows = $(".case:checked").closest("tr");
This returns a jQuery object that contains all of your table rows housing checked checkboxes.
Call getElementsByName will give you an array of references of your checkboxes.
Loop the array in order to get the values.
var arr = document.getElementsByName("case");
for(i = 0; i < arr.length; i++){
if(arr[i].checked){
doSomething;
}
}

Categories

Resources