Liam Liam - 6 months ago 6
HTML Question

Checkbox Rules Script applies to a single row of checkboxes, but I can't get it to apply to multiple rows

I have made a row of checkboxes that have certain rules applied to them:
If 'Voice' or 'Mail' is checked - then 'Select' must automatically checked too.

However if 'Select' is unchecked by the user - then both 'Voice' and 'Mail' must be unchecked automatically too.

I have the fiddle for this here:

https://jsfiddle.net/monkeyroboninja/omym4efh/18/

This works fine but now I want it to apply to multiple table rows, each row able to contain their own set of values in those checkboxes. So I thought I'd need to use a loop to go through each row, change the

<td>
id attributes to class attributes (since there is multiple ones now), and also use the (this) keyword to make my jQuery apply to only the table row currently through the loop. So with this thought I made this:
https://jsfiddle.net/monkeyroboninja/oc18um8t/11/

and here is that code in case its easier for you:

$(".tableRow").each(function() {

var $select = $((this) ".select");
var $voice = $((this) ".voice");
var $mail = $((this) ".mail");

$($(this) $voice).click(function(){
if($(this).val('TRUE')){
$((this) $select).prop('checked', true);
}
});

$($(this) $mail).click(function(){
if($(this).val('TRUE')){
$($select).prop('checked', true);
}
});

$($(this) $select).click(function(){
if($(this).val('FALSE')){
$($voice).prop('checked', false);
}
});

$($(this) $select).click(function(){
if($(this).val('FALSE')){
$($mail).prop('checked', false);
}
});
});


Aaand it didn't work! I think its the use of the (this) keyword I have wrong but what I found on the web doesn't help (or I can't understand). I do seem to have that key word everywhere!
Is anyone able to suggest where I went wrong?

Answer

try this

$(".tableRow").each(function() {
  var row = this;
  $(row).find(".voice").click(function(){
    if($(this).val('TRUE')){
      $(row).find('.select').prop('checked', true);
    }
  });

  $(row).find(".mail").click(function(){
    if($(this).val('TRUE')){
      $(row).find('.select').prop('checked', true);
    }
  });

  $(row).find(".select").click(function(){
    if($(this).val('FALSE')){
      $(row).find('.voice').prop('checked', false);
      $(row).find('.mail').prop('checked', false);
    }
  });                              
                
});

Comments