Search code examples
jqueryloopscheckboxhidden

jQuery to disable checkbox based off value of corresponding hidden field


I have 91 checkboxes and 91 corresponding hidden elements. I'm attempting to loop through the hidden elements and those which have a value of 0, disable the corresponding checkbox. The template variable will get replaced with either 0 or 1 before the page is served up.

Here is some of my markup:

    <input type="hidden" class="h_status" name="enabled_25" value="0">
<br><input type="checkbox" class="c_status" name="perm_25" value="1"> Create RPL Invoice

<input type="hidden" class="h_status" name="enabled_50" value="0">
<br><input type="checkbox" class="c_status" name="perm_50" value="1"> Uncancel Invoice 

<input type="hidden" class="h_status" name="enabled_49" value="0">
<br><input type="checkbox" class="c_status" name="perm_49" value="1"> Flag As Fraud

<input type="hidden" class="h_status" name="enabled_54" value="1">
<br><input type="checkbox" class="c_status" name="perm_54" value="1"> Change Initials

<input type="hidden" class="h_status" name="enabled_3" value="1">
<br><input type="checkbox" class="c_status" name="perm_3" value="1"> View/Edit CC Info

<input type="hidden" class="h_status" name="enabled_52" value="1">
<br><input type="checkbox" class="c_status" name="perm_52" value="1"> View Invoice History

<input type="hidden" class="h_status" name="enabled_47" value="1">
<br><input type="checkbox" class="c_status" name="perm_47" value="1"> Reprint Pull Copy

My initial attempt at the jQuery does not work (none of the checkboxes get disabled). I loop through the hidden elements using the each function and the h_status selector. Then, if the value of any element is blank or 0, disable the checkbox using the c_status selector.

Here's my code so far (please be gentle, I'm still learning):

$('.h_status').each(function(){

    var tempval = $(this).val();

    if ( tempval == "" || tempval == 0 ){       
        $('.c_status').prop('disabled', true);      
    }
});

Solution

  • Maybe this will work:

    $('.h_status').each(function(){
        var d = $(this).val() == 0 ? false : true;
        var name = $(this).attr('name').split('_');
        $('input[name="perm_'+name[1]+'"]').prop('disabled', d);
    });
    

    Disclaimer: untested