if i have a table with an infinite which has an input type checkbox. Each check box is marked with an id eg. #det1, #det2 , #det3 how would i write my JS loop to check if that certain checkbox is checked to perform the function on it, without writing out each id ,because this id is also incremented based on the product uploader so for each product uploaded it will just add 1 to the id,at the end i could sit with allot of id's.
javascript that works adding the id manually:
$('#details1, #details2').on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
So that works but because have so many id's based on my tr's i would just like to do a loop and check if that id exist (it could be id = #details999) and if it does do function on.change.
(for each product ill upload the id adds 1 to it eg. product1 = #details1 , product2 = #details2, etc...)
There might be a better way of implementing the idea but as im newbie i am open to any suggestions.
What i tried:
for (var i = 0; i < ?; i++) {
$('#details'+ i).on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
})
}
i know ? means nothing but i realized i cant set a limit to that also don't want a infinite loop so i'm kind of stuck.
Add a common class to the select elements and use that to target them
<input type="checkbox" id="details1" class="details-checkbox">
<input type="checkbox" id="details2" class="details-checkbox">
<input type="checkbox" id="details3" class="details-checkbox">
and then use
$('.details-checkbox').on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
I would use event delegation:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
$('table').on('change', 'input[type="checkbox"]', function(e) {
var row = $(this).closest('tr').next('tr');
$(row).toggle($(this).prop('checked'));
})
tr.hidden { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td>1</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 1</td></tr>
<tr><td>2</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 2</td></tr>
<tr><td>3</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 3</td></tr>
<tr><td>4</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 4</td></tr>
</tbody>
</table>
$('input:checkbox[id*=details ]').on('change',function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
Related
First off I'd like to say that I know that this question was already asked a lot of times but I can assure you that I tried using all the answers I could find but all failed.
So first off I have a jQuery Datatable looking like this (I'm using laravel so that's why there's this foreach) :
<table>
<thead>
<tr>
<th id="head-cbx"><input type="checkbox" name="example"></th>
<th id="head-xcode">XCODE</th>
<tr>
</thead>
<tbody>
#foreach($xcodes as $xcode)
<tr>
<td id="head-cbx"><input type="checkbox" class="xcode-cbx" name="xcodes[]"></td>
<td>{{ $xcode }}</td>
<tr>
#endforeach
</tbody>
</table>
The obvious objective is to have a checkbox that allows me to check / uncheck all the others.
For the jQuery part I tried the following solutions :
$(document).ready(function(){
var headcbx = $('#head-cbx');
headcbx.change(function(){
if (headcbx.is(':checked')) {
//uncheck all
} else {
//check all
}
});
}
then
$(document).ready(function(){
var headcbx = $('#head-cbx');
headcbx.change(function(){
if ($(this).is(':checked')) {
//uncheck all
} else {
//check all
}
});
}
then
$(document).ready(function(){
var headcbx = $('#head-cbx');
headcbx.change(function(){
if (this.is(':checked')) {
//uncheck all
} else {
//check all
}
});
}
then I changed my test from
if (this.is(':checked'))...
to
if(this.checked)
and then to
if(this.prop('checked)
of course, each time I tried the variants
this
headcbx
$(this)
$('#head-cbx')
After that I tried using
$(document).on('change', '#head-cbx', function(){...})
with all the same variants that I listed above.
Anyway, I always have the same result : false.
So I'm beginning to get frustrated and I could use the help because I think I'm missing something obvious somewhere but I can't seem to find it...
Thanks :)
Your selector is wrong, as head-cbx refers to <TD> element not checkbox So either change selector
var headcbx = $('#head-cbx :checkbox');
Note: this.checked/$(this).is(':checked')/$(this).prop('checked) would work
OR, Fix HTML
<th><input id="head-cbx" type="checkbox" name="example"></th>
The issue is here:
var headcbx = $('#head-cbx');
&
<td id="head-cbx">
the id you are ussing in event listener is of td, not of checkbox. So change it to something like:
var headcbx = $('#head-cbx :checkbox');
I'm using tables of MDL lib. https://getmdl.io/components/index.html#tables-section
But there are no docs how I can retrieve checked values about.
I found only this solution, but this not helping at all:
var checkboxes = document.getElementById('team-table-id')
.querySelector('tbody').querySelectorAll('.mdl-checkbox__input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function() {
console.log(this)
// returns <input type="checkbox" class="mdl-checkbox__input">
// how can I assign and retrieve value to/from this input?
});
}
How can I assign a value to checkbox/input of table rows at all?
How can I retrieve single checked values?
How can I handle "select all" event and get data of all rows?
Ok, I didn't find solution.
So I make my own for temporary:
1) Assign some class for tr's, so it can be found when check event happend
2) assign value for tr's. It can be serialized values or smth like that
3) listen check event and get data
Markup:
<table id="team-table-id" width="100%" class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
<thead>
<tr class="row-info" data-value="all">
<th class="mdl-data-table__cell--non-numeric">Donation Invoice</th>
<th>Donation Name</th>
<th>Donation price</th>
</tr>
</thead>
<tbody>
<tr class="row-info" data-value="one more value">
<td class="mdl-data-table__cell--non-numeric">I-20170419120440</td>
<td>Some Donation Name</td>
<td>$2.90</td>
</tr>
<tr class="row-info" data-value="another value">
<td class="mdl-data-table__cell--non-numeric">C-20170419120454</td>
<td>Anothre</td>
<td>$1.25</td>
</tr>
<!--etc...-->
Javascript:
window.findAncestor = (el, cls) => {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
let checkboxes = document.getElementById('team-table-id')
.querySelectorAll('.mdl-checkbox__input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function() {
console.log(findAncestor(this, 'row-info'))
});
// Returns parent table row, so you can get selected data.
// For example <tr data-value="some value" class="row-info">....
Please, feel free to suggest right one.
UPD:
This approach dnt have bugs and can hanlde all checked values, so I've marked this as "solved".
Have a look at https://github.com/google/material-design-lite/issues/1210 where several solutions (work-around) are presented depending on the version of MDL
I am following this (work-around)
On window.onload I am adding onclick attribute to all checkbox to call function getCheckValue(this), this function traverse through dom to get innerHTML of each td in tr
window.onload=function(){
var checkAll=document.getElementsByClassName('mdl-checkbox__input')
for(var i=0;i<checkAll.length;i++){
checkAll[i].setAttribute('onclick','getCheckValue(this)')
}
}
function getCheckValue(obj){
if(obj.checked){
/*th is checked in thead*/
if(obj.parentElement.parentElement.parentElement.parentElement.nodeName=='THEAD'){
var trs=obj.parentElement.parentElement.parentElement.parentElement.nextElementSibling.children
for(var i=0;i<trs.length;i++){
var tds=trs[i].getElementsByTagName('td')
for(var j=1;j<tds.length;j++){
console.log(tds[j].innerHTML)
}
}
}
else{
/*td inside tbody is checked*/
var tds=obj.parentElement.parentElement.parentElement.getElementsByTagName('td')
for(var i=1;i<tds.length;i++){
console.log(tds[i].innerHTML)
}
}
}else{
/* uncheck th checkbox of thead*/
if(obj.parentElement.parentElement.parentElement.parentElement.nodeName!='THEAD'){
obj.parentElement.parentElement.parentElement.parentElement.previousElementSibling.firstElementChild.firstElementChild.firstElementChild.classList.remove('is-checked')
obj.parentElement.parentElement.parentElement.parentElement.previousElementSibling.firstElementChild.firstElementChild.firstElementChild.firstElementChild.checked=false
}
}
}
Plunker link for demonstration
I have dynamic table that has table cell with checkbox field. This fields are populated from DB so my table is dynamic. I would like to loop through checkboxes based on their class name. In that loop I want to check value for each check box. For example if value is equal 1 I want checkbox to be checked, if not unchecked. Alo I'm not sure if possible but I would like to set unique ID for each of these check boxes. Since my table is dynamic my fields need to have unique ID's. Here is example of my code:
<table>
<thead>
<tr>
<th>#</th>
<th>Time Slots</th>
<th>Block</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>~(SLOT_LABEL)</td>
<td>
<span>
<input type="checkbox" name="CF-[Events]" class="block" id="block_"+Value that will make this ID unique. value="~(SLOT_ID)"/>
</span>
</td>
</tr>
</tbody>
</table>
Also in current language that I work with to read values from DB I have to use NAME tag. If anyone can help please let me know. Thank you.
You can use the attribute selector to retrieve elements by both their name and value. Try this:
$('input[name="CF-[Events]"][value="1"]').prop("checked", true);
Working example
If you don't want a jQuery solution, it is also possible to fetch these elements with the querySelector:
var inputs = document.querySelectorAll("input.block");
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
}
you can do it in jquery by each loop
$('.ClassName').each(function(i, o) {
// o is object in your case checkbox
// i is index
// your code
});
$("input[name='CF-[Events]']").each(function() {
if($(this).val() === "1")
{
$(this).prop("checked", true);
}
});
I've tried making a function that is triggered by whenever a checkbox inside a table is checked but that didn't work well. I've tried making a function located in a $(document).ready but it didn't also work.
this is my html code
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
this is my function
$(document.ready)(function () {
$("#row input:checked'").each(function(){
$('#select').click(function(){
alert('clicked');
});
});
My main goal is counting the selected checkboxes and not allowing the user to check more than 3. But for now I'm trying to make a function that would recognize whenever a checkbox is selected
});
Your DOM ready should be $(document).ready(function(){...
You shouldn't bind click to each checkbox by iterating through only checked ones
Bind using event delegation, and then check the state on click.
As per your question, your problem is to disallow user to check more than three checkboxes.
You could do that by doing a length of all checked inputs, and then overriding new checks if the length exceeds three:
Demo: http://jsfiddle.net/abhitalks/uERSd/1/
// bind click to all input of type checkbox inside #row via delegation
$("#row").on("click", "input[type='checkbox']", function() {
// check the length i.e. total number of inputs which are currently checked
var tot = $("#row input[type='checkbox']:checked").length;
if (tot > 3) {
// disallow new checks if three are already checked
this.checked = false;
}
});
To recognize whenever checkbox is selected, you can use:
$("#select").change(function() {
if(this.checked) {
alert('clicked');
}});
Try this : Here document.ready syntax is corrected and jquery modified to get total count of checked checkboxes inside td with id='row'
$(document).ready(function(){
$("#row input[type='checkbox']").click(function(){
var count = $("#row input[type='checkbox']:checked").length;
alert("total checked checkbox is : "+count);
});
});
This code will work
$(document).ready(function() {
$("#select").change(function() {
if(this.checked) {
alert('checked');
}});
});
Your HTML
<table class="tableTable">
<tr id="tableTr">
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
<td id='row1'><input type='checkbox' name='helloname' value="helloval" id='select1'> hello1 </td>
<td id='row2'><input type='checkbox' name='helloname' value="helloval" id='select2'> hello2 </td>
<td id='row3'><input type='checkbox' name='helloname' value="helloval" id='select3'> hello3</td>
</tr>
</table>
JQUERY
$(document).ready(function(){
$("#tableTr").on("click", "input[type='checkbox']", function() {
var count = $("#tableTr input[type='checkbox']:checked").length;
if (count > 3) {
this.checked = false;
alert("only 3 items can be checked");
}
});
});
I´m new in JQuery and I have a trouble. I want to read a specific cell value from a table row where I have a checkbox. I have an event that handles the checkbox checked event. This is my code:
$("#businesses input:checkbox").change(function (
var $this = $(this);
if ($this.is(":checked")) {
//Here I want to read a value from a column in a row where is the checkbox
} else {
//Here I want to read a value from a column in a row where is the checkbox
}
});
I have a table called "businesses" and it has this format
<table id="businesses">
<tr>
<th>Select Value</th>
<th>Value</th>
</tr>
<tr>
<td><input type="checkbox" class="selectedService" title="Seleccionar" /></td>
<td>125</td>
</tr>
<tr>
<td><input type="checkbox" class="selectedService" title="Seleccionar" /></td>
<td>126</td>
</tr>
</table>
What I want to do, is that when I select a checkbox, get the value field of its row.
If I press the first checkbox I want to get 125.
Thanks!!!
Starting from your checkbox (this in the event handler function), you need to go up to the containing <td> element, across to the next <td> element, then get its text:
$('#businesses input:checkbox').change(function(e) {
if(this.checked) {
var value = parseInt($(this).closest('td').next('td').text(), 10);
// above will convert it from a string to an integer
}
else {
// same as above? Seems redundant
}
});
Use siblings() of the parent:
$this.closest('td').siblings().text();
If this is not the only other <td> siblings() would return all of the rest so use appropriate selector to filter them.
You could access it with:
$this.parent().next().text();
Try this...
$("#businesses input:checkbox").on ('change', function (e)
if ($(this).is(":checked")) {
$( e.target ).closest("td").text();
} else {
//Here I want to read a value from a column in a row where is the checkbox
}
});
Greetings.