Javascript check boxes based on text in rows - javascript

I am trying to convert this: Select table row and check checkbox using JQuery
into normal javascript, since I'm in a situation where I cannot use jquery.
Here is the orignal
$("table tr").each(function () {
if ($(this).find("td:eq(1)").text().trim() == '2013-03-21') {
$(this).find("input[type=checkbox]").attr("checked", true);
}
});
This is what I have so far, and I'm sure its way off:
var elements = [].slice.call(document.querySelectorAll("table tr"));
Array.prototype.forEach(elements, function(){
var tdText = this.querySelectorAll("td").textContent
if (tdText == '2013-03-21') {
this.querySelectorAll("input[type=checkbox]").setAttribute("checked", true);
}
});
This is the original table:
<table>
<tr>
<td>Record1</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record2</td>
<td>2013-03-22</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record3</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>

querySelectorAll() returns a nodeList of elements.
You need to iterate those and deal with each instance or use the index you want like:
element.querySelectorAll("td")[0]

The code var tdText = this.querySelectorAll("td").textContent will return an undefined textContent because you are referring to the tr's NodeList. You can loop through it and then you can get the td's content:
let rows = Array.prototype.slice.call(document.querySelectorAll('table tr'));
let textDate = '2013-03-21';
rows.map((row) => {
let cells = Array.prototype.slice.call(row.querySelectorAll('td'));
for (let i = 0, length = cells.length; i < length; i++) {
if (cells[i].textContent === textDate) {
let cb = row.querySelectorAll('input[type=checkbox]');
cb[0].checked = true;
return;
}
}
});

Use ElemCollection.forEach.call instead of using Array#slice.call as HTMLCollection does not have forEach method
Use [1] index while selecting text from td element
this in Array#forEach does not refer to element, use first argument of Array#forEach callback function which is item of array
Array.prototype.forEach.call(document.querySelectorAll("table tr"), function(elem) {
var tdText = elem.querySelectorAll("td")[1].textContent;
if (tdText === '2013-03-21') {
elem.querySelector("input[type=checkbox]").setAttribute("checked", true);
}
});
<table>
<tr>
<td>Record1</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record2</td>
<td>2013-03-22</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record3</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>

Related

Code isn’t executed after removing rows in a table

I wrote a JavaScript function to remove selected rows in a table and it works fine but when I try to write some jQuery to change color of some button it doesn’t work. I have no clue what am I doing wrong.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button type="button" onclick="DeleteRow()" class="btn"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
<script>
function DeleteRow() { //this function delete selected rows from table
var i, chkbx, td;
var table = document.getElementById("myTable"); //table itself
var rows = table.getElementsByTagName("tr"); //rows in table-body
var numRows = rows.length; //number of rows
for (i = 1; i < numRows; i++) { //in this "for loop" , I try to remove selected rows
td = rows[i].getElementsByTagName("td")[0];
chkbx = td.getElementsByTagName("input")[0];
if (chkbx.checked == true) {
table.deleteRow(i);
--i; //each time we delete one row we decrease i
}
}
$(document).ready(function() {
$(".btn").css("background-color", "#ff0000");
}); //this jquery wont work
}
</script>
</body>
</html>
There are couple of issues in your loop causing an error, so I've fixed those, and moved your inline event listener to the JS file. Comments in the code. I also switched from jQuery to vanilla JS because there's no reason to use it if you're using vanilla JS everywhere else.
// Grab the button and add an click event for DeleteRow
document.querySelector(".btn").addEventListener('click', DeleteRow, false)
function DeleteRow() {
var i, chkbx, td;
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
// When removing items from the DOM it's usually a good idea
// to reverse the loop and simply use the length of the array.
// That way you don't have to decrement the index manually
for (let i = rows.length - 1; i > 0; i--) {
td = rows[i].getElementsByTagName("td")[0];
chkbx = td.getElementsByTagName("input")[0];
if (chkbx.checked == true) {
table.deleteRow(i);
}
}
// You don't have to use jQuery (it's a waste if everything
// else is native JS. Here we use `this` which is the element attached
// the click event
this.style.backgroundColor = '#ff0000';
}
<button type="button" class="btn"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
A short refined version of your code could be like below. This will only change button background if the row is selected / deleted.
function DeleteRow() { //this function delete selected rows from table
var i, chkbx, td;
var table = $("#myTable tbody>tr input:checked"); //table itself
table.each(function() {
$(this).parent().parent().remove();
})
if (table.length) {
return true;
}
}
$(document).ready(function() {
$('#del').click(function() {
if (DeleteRow()) {
$(".btn").css("background-color", "#ff0000");
}
}); //this jquery wont work
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" id="del"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
If you already have jQuery, why are you mixing it with plain js? You can do this in jQuery very simply:
function DeleteRow() { //this function delete selected rows from table
$('input[type=checkbox]').each(function () {
if ($(this).prop('checked')) {
$(this).closest('tr').remove();
}
});
$(".btn").css("background-color", "#ff0000");
}

Jquery check the checkbox in td before

I have a table in html with td contains a checkbox input like this
<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
<script>
$('[type=checkbox]').change(function () {
if($(this).is(":checked")) {
$(this).closest('td').prev().find('input[type=checkbox]').prop('checked', true);
}
});
</script>
I wanna create a function in jquery that when I check a checkbox the one above it is checked (example if td3 is checked then td1 is checked also) but the one i used check the input next to this and not above it.
Thanks for your help
One approach, though using plain JavaScript rather than jQuery, is to assign an event-listener, for the change event, to the parent <td> element. From there find its cellIndex property to find the correct cell, and descendant <input>, in the previous row, to change:
// retrieve the <table> element, by its id property:
var table = document.getElementById('my_table'),
// find all the <td> elements within the <table>:
cells = table.getElementsByTagName('td'),
// convert the collection of <td> elements
// into an Array (using an ES5 approach because
// of my work browser):
cellArray = Array.prototype.slice.call(cells, 0);
// if ES6 is available to you the following would
// be more concise:
// cellArray = Array.from( cells );
// iterating over the Array of cells:
cellArray.forEach(function(cell) {
// 'cell', the first argument, is a reference to
// the current array-element (a <td> node)
// of the Array over which we're iterating.
// here we add the event-listener for the 'change'
// event, using the anonymous method to handle the
// functionality:
cell.addEventListener('change', function(e) {
// 'this' is the <td> element, the 'cell' variable:
var index = this.cellIndex,
// e is the event-object passed into the
// anonymous function,
// e.target is the element that triggered
// the event we were listening for, the
// descendant <input>; the checked property
// is Boolean, and will return true if it's
// checked and false if not:
checked = e.target.checked,
// the parentNode of a <td> is the <tr>:
row = this.parentNode,
// the previous <tr> element is the
// previousElementSibling (the first
// of the element's previous-siblings
// that is also an element, so excluding
// textNodes, commentNodes etc:
previousRow = row.previousElementSibling;
// if we have a previous row:
if (previousRow) {
// we find its children (which are elements,
// children is different from childNodes):
previousRow.children[index]
// we then find the first, if any, <input>
// element with a 'type' property of 'checkbox':
.querySelector('input[type=checkbox]')
// and set its checked state to the same
// Boolean value as the <input> which fired the
// the change event:
.checked = checked;
}
});
});
var table = document.getElementById('my_table'),
cells = table.getElementsByTagName('td'),
cellArray = Array.prototype.slice.call(cells, 0);
cellArray.forEach(function(cell) {
cell.addEventListener('change', function(e) {
var index = this.cellIndex,
checked = e.target.checked,
row = this.parentNode,
previousRow = row.previousElementSibling;
if (previousRow) {
previousRow.children[index].querySelector('input[type=checkbox]').checked = checked;
}
});
});
<table id="my_table">
<tr>
<td>
<input type="checkbox" name="td1">
</td>
<td>
<input type="checkbox" name="td2">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td3">
</td>
<td>
<input type="checkbox" name="td4">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td5">
</td>
<td>
<input type="checkbox" name="td6">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td7">
</td>
<td>
<input type="checkbox" name="td8">
</td>
</tr>
</table>
JS Fiddle demo.
References:
Array.from().
Array.prototype.forEach().
Array.prototype.slice().
document.getElementById().
document.querySelector().
document.querySelectorAll().
HTMLTableCellElement properties, including cellIndex.
EventTarget.addEventListener().
Node.childNodes.
Node.parentNode.
NonDocumentTypeChildNode.previousElementSibling.
ParentNode.children.
Use index() to get index of clicked checkbox td and accordingly check another previous checkbox
$('[type=checkbox]').change(function () {
index = $(this).closest('td').index();
if($(this).is(":checked")) {
$(this).closest('tr').prev().find('input:checkbox').eq(index).prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
Check the following example. It uses index() to get the clicked cell's index. Then selects the previous row and finds the respective checkbox:
$('[type=checkbox]').change(function () {
var that = $(this);
// Get clicked cell's index
var index = that.closest('td').index();
// Get previous row's cell with same index
var aboveTd = that.closest('tr').prev('tr').find('td').eq(index).find('input[type=checkbox]');
// Toggle checked state
aboveTd.prop('checked', that.is(":checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
You can do something like this:
$('[type=checkbox]').change(function() {
if ($(this).closest('tr').prev().has('input[type="checkbox"]')) {
var idx = $(this).closest('td').index();
$(this).closest('tr').prev().find('td:eq(' + idx + ') input[type=checkbox]').prop('checked', this.checked);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my_table">
<tr>
<td>
<input type="checkbox" name="td1">
</td>
<td>
<input type="checkbox" name="td2">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td3">
</td>
<td>
<input type="checkbox" name="td4">
</td>
</tr>
</table>

Unable to remove rows from table

I am having the table with following data in it
<table>
<tr>
<td> cat </td>
<td> dog </td>
</tr>
<tr>
<td> hen </td>
<td> cock </td>
</tr>
</table>
I would like to delete the row based on the particular data given in table.
But I don't have any idea on how to delete the rows based on the particular data
Try this:
var table = document.querySelector('table');
var filterInput = document.querySelector('#filter');
filterInput.onkeyup = function () {
var val = this.value;
var td = table.getElementsByTagName('td');
var rows = [];
[].slice.call(td).forEach(function (el, i) {
if (el.textContent === val) {
rows.push(el);
}
});
rows.forEach(function(el) {
el.parentNode.style.display = 'none';
});
};
<input type="text" id="filter" placeholder="Hide row containing...">
<table>
<tr>
<td>cat</td>
<td>dog</td>
</tr>
<tr>
<td>hen</td>
<td>cock</td>
</tr>
</table>
Find the required element and then use style property to hide it. In the example, I went onto hide the table data element corresponding to the data dog.
var tds = $("td");
for(var i =0 ; i< tds.length ; i++)
{
var tdval = tds[i].innerHTML;
if(tdval.trim()=="dog")
{
document.getElementsByTagName("td")[i].style.display = "none";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td> cat </td>
<td> dog </td>
</tr>
<tr>
<td> hen </td>
<td> cock </td>
</tr>
</table>

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

JavaScript summing of textboxes

I could really your help! I need to sum a dynamic amount of textboxes but my JavaScript knowledge is way to week to accomplish this. Anyone could help me out? I want the function to print the sum in the p-tag named inptSum.
Here's a function and the html code:
function InputSum() {
...
}
<table id="tbl">
<tbody>
<tr>
<td align="right">
<span>June</span>
</td>
<td>
<input name="month_0" type="text" value="0" id="month_0" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>July</span>
</td>
<td>
<input name="month_1" type="text" value="0" id="month_1" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>August</span>
</td>
<td>
<input name="month_2" type="text" value="0" id="month_2" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>September</span>
</td>
<td>
<input name="month_3" type="text" value="0" id="month_3" onchange="InputSum()" />
</td>
</tr>
</tbody>
</table>
<p id="inputSum"></p>
function InputSum() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("month_") == 0)
alert(inputs[i].value);
}
}
With a little jQuery, you could do it quite easily, using the attribute starts with selector. We then loop over them, parses their values into integers and sum them up. Something like this:
function InputSum() {
var sum = 0;
$('input[id^="month_"]').each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
}
You could even get rid of the onchange attributes on each input if you modify the code to something like this:
$(function () {
var elms = $('input[id^="month_"]');
elms.change(function() {
var sum = 0;
elms.each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
});
});
function InputSum() {
var month_0=document.getElementById("month_0").value;// get value from textbox
var month_1=document.getElementById("month_1").value;
var month_2=document.getElementById("month_2").value;
var month_3=document.getElementById("month_3").value;
// check number Can be omitted the
alert(month_0+month_1+month_2+month_3);//show result
}

Categories

Resources