Grab a certain table row - javascript

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]").

Related

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>

How do I locate elements in the same row as another in a dynamic table?

I am making a page that contains a table with a button to add a row. It is a table for users to input data, and will eventually be submitted to a database.
Currently, I have a price and a quantity field in each row. When either of them change, I want to calculate the total and write it to another cell.
This is my event handler (wrapped in $(document).ready()):
$(".quantity_input, .price_input").change(function () {
console.log(this.value);
cal_total();
});
This is my current code:
function cal_total() {
if (isNaN(parseFloat(this.value))) {
alert("You must enter a numeric value.");
this.value = "";
return;
}
var cell = this.parentNode;
var row = cell.parentNode;
var total = parseFloat($("#items_table tr").eq(row.index).find("td").eq(3).find("input").first().val()) * parseFloat($("#items_table tr").eq(row.index).find("td").eq(4).find("input").first().val());
if (!isNaN(total)) {
$("#items_table tr").eq(row.index).find("td").eq(5).html(total.toFixed(2));
}
}
And this is what the inputs look like:
<input type='text' class='fancy_form quantity_input' name='quantities[]' size='4' style='text-align:center;border-bottom:none;'>
In addition to my original question, the event is never fired. Can anyone see why?
But more importantly, is this the best way to retrieve the values? I really don't think so but I cant come up with anything more clever.
Thank you!
you have to pass paremeter to calc_total to define input or tr
try this code
$(".quantity_input, .price_input").change(function () {
$(".quantity_input, .price_input").change(function () {
cal_total(this);
});
});
function cal_total(elem){
var row=$(elem).closest("tr")
var quantity=row.find(".quantity_input").val()-0
var price=row.find(".price_input").val()-0
var total=quantity * price
row.find(".totl_input").val(total)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</td>
</tr>
<tr>
<td>
<input class="quantity_input" />
</td>
<td>
<input class="price_input" />
</td>
<td>
<input class="totl_input" />
</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

Disable Or Enable Checkbox Array Using Javascript

I have Following codes:
<html>
<head>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox" name="ck[]" value="sakit">
</td>
<td>
<input type="checkbox" name="ck[]" value="izin">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ck[]" value="sakit">
</td>
<td>
<input type="checkbox" name="ck[]" value="izin">
</td>
</tr>
</table>
</body>
</html>
How can i disable checkbox in first tr element without make changes in second tr, otherwise i can disable checkbox in second tr element without make changes in first tr?
You can use document.querySelector to target elements using a css selector.
For targeting the first <tr>
document.querySelector('tr:first-child input').disabled = true;
or for targeting the second <tr>
document.querySelector('tr:last-child input').disabled = true;
You can simply disable a checkbox with: CheckboxObject.disabled = true;
In HTML you all you have to do is:
<input type="checkbox" name="ck[]" value="sakit" disabled>
in JS you would do this:
var fields = document.getElementsByTagName("input");
for (var i = 0; i < fields.length; i++) {
if (fields[i].type == "checkbox")
fields[i].disabled = true;
}
this would disable the first checkbox on page.. if you need something different, let me know.

click anywhere on a table row and it will check the checkbox its in...?

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.

Categories

Resources