Ylama Ylama - 3 years ago 184
HTML Question

loop using JavaScript based in html id

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.

Answer Source

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();
    }
 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download