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>
Related
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>
I want to get value of radio in table using click event.Note , get value of radio in column
<table id="div_table" width="500px" border="2px" cellpadding="2" cellspacing="2" >
<tr>
<td >Column Name1</td>
<td>Column Name2</td>
<td >Column Name3</td>
</tr>
<tr >
<td >PN1</td>
<td ><input type="radio" name="RD_CHECK" value="ABC">ABC</td>
<td ></td>
</tr>
<tr >
<td >PX2</td>
<td ><input type="radio" name="RD_CHECK" value="XYZ">XYZ <input type="radio" name="RD_CHECK" value="CBA">CBA</td>
<td ><input type="radio" name="RD_CHECK" value="123">123 <input type="radio" name="RD_CHECK" value="456">456</td>
</tr>
</table>
Ok , Example: I check radio of column2 but it not work.
$(document).ready(function ()
{
$('body').on('click','#div_table tbody tr', function ()
{
if ($("input[type='radio']").is(':checked') == true && $(this).find('td:eq')==1)
{
//value of radio in Column2
alert('This is Column 2 and value = '+$("input:checked").val());
}
else
{
// value of radio in Column3
alert('This is Column 3 and value = '+$("input:checked").val());
}
});
});
Give me advised.Thank guys.
$("input[type='radio']").is(':checked') == true Will get the checked property of only the first matching <input>. If your first radio isn't checked, this fails.
$(this).find('td:eq') == 1 Will always be true since even a jQuery constructor with no matches returns an object (truthy value).
Instead, attach the event to the radio buttons themselves. You can get the column by finding the .index() of the .closest() <td>. To get the value simply use the context of your event:
$(document).ready(function () {
$('body').on('click', '#div_table tr :radio', function () {
var col = $(this).closest('td').index();
alert('This is Column ' + col + ' and value = ' + this.value);
});
});
JSFiddle
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
I have a table with a radio button per row.
<table id="t1">
<tr><td><input type="radio" onclick="grab_row()" value=1></td><td>Data1<td>Data11</td></tr>
<tr><td><input type="radio" onclick="grab_row()" value=2></td><td>Data2<td>Data22</td></tr></table>
I would like to have a function that grabs the values of the row selected via radio.
my function:
function grab_row () {
var radio = $("input[name=t1]:checked").val();
}
The function only grabs the radio id that is currently selected.
for example, if the first radio is clicked, Data1 and Data11 are returned.
Thanks
Here's my interpretation of what you're looking for
html
<table>
<tr>
<td>
<input type="radio" value="1" name="myradio" />
</td>
<td>Data1</td>
<td>Data11</td>
</tr>
<tr>
<td>
<input type="radio" value="2" name="myradio" />
</td>
<td>Data2</td>
<td>Data22</td>
<td>Data222</td>
</tr>
js
$("input:radio[name=myradio]").click(function () {
var myvals = [];
var elem = $(this).parent().next();
while (elem.prop("tagName") == "TD") {
myvals.push(parseInt(elem.html().substring(4)));
elem = elem.next();
}
console.log(myvals);
});
I assumed that you just need the integers after the "Data" string, but you can grab the entire content of the TD element with just the .html() and leaving out the .substring(4)
fiddle
When you use .val() when using a selector that returns multiple elements, it will only return the value of the first element. Instead, you need to iterate through them using .each().
var values = [];
$("input[name=t1]:checked").each(function(idx, val) {
//spin through and collect each val
values.push($(val).val());
})
console.log(values); //view values in console
This should be your jQuery:
$("input[type=radio]").click(function () {
console.log($(this).val());
});
and this should be your HTML:
<table id="t1">
<tr>
<td>
<input type="radio" name="foo" value="1" />
</td>
<td>Data1</td>
<td>Data11</td>
</tr>
<tr>
<td>
<input type="radio" name="foo" value="2" />
</td>
<td>Data2</td>
<td>Data22</td>
</tr>
</table>
jsFiddle example
Note that you can also use $("input[name=foo]") instead of $("input[type=radio]").
I'm trying to figure out how to do this, but I can't find it out. Basically I want to be able to click anywhere on a table row and it will check/ unchecked the checkbox its in. I know it's possible because that's what PHPMyAdmin does...
here is my table row
<tbody>
<tr id="1" onclick="selectRow(1)"><td width="20px"><input type="checkbox" id="1" name="1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr id="2" onclick="selectRow(2)"><td width="20px"><input type="checkbox" id="2" name="2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
<script type="text/javascript">
function selectRow(row)
{
var firstInput = row.getElementsByTagName('input')[0];
firstInput.checked = !firstInput.checked;
}
</script>
...
<tbody>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk1" name="chk1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
Note: You've also got collisions on ids. Your ids should be unique.
Here's an alternative with programmatic binding:
document.querySelector("table").addEventListener("click", ({target}) => {
// discard direct clicks on input elements
if (target.nodeName === "INPUT") return;
// get the nearest tr
const tr = target.closest("tr");
if (tr) {
// if it exists, get the first checkbox
const checkbox = tr.querySelector("input[type='checkbox']");
if (checkbox) {
// if it exists, toggle the checked property
checkbox.checked = !checkbox.checked;
}
}
});
<table>
<tbody>
<tr>
<td>
<input type="checkbox" id="chk1" name="chk1" />
</td>
<td>1</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk2" />
</td>
<td>2</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk3" />
</td>
<td>2</td>
<td>2011-04-21 25:30:16</td>
<td>action</td>
</tr>
</tbody>
</table>
You don't need JavaScript for this:
td label {
display: block;
}
<td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td><label for="chk2">2</label></td><td><label for="chk2">2011-04-21 22:04:56</label></td><td><label for="chk2">action</label></td>
Just labels and a little CSS.
Try this one out...
$("tr").click(function() {
var checkbox = $(this).find("input[type='checkbox']");
checkbox.attr('checked', !checkbox.attr('checked'));
});
http://jsfiddle.net/dVay8/
Since this question getting so many views and the accepted answer has a small issue.
The issue is when you click on the checkbox it won't change. Actually what happens is the checkbox toggles twice. Because of we clicked on the checkbox and the table row as well. So here is a proper solution with a fix.
$('tr').click(function(event){
var $target = $(event.target);
if(!$target.is('input:checkbox'))
{
$(this).find('input:checkbox').each(function() {
if(this.checked) this.checked = false;
else this.checked = true;
})
}
});
Good luck devs.