Search code examples
javascriptjquerycheckboxinputdisabled-input

Disable input if checkbox is ticked on page load AND when it is clicked


I've looked at loads of questions that describe how to check weather a check box is checked or not but none of them gives the answer I need. I want to check whether the check box is checked on page load and if it is, disable an input. Then I need the disabled input to be changed when the box is checked/uncheked after page load.

This is what I have:

jQuery(document).ready(function($) {
    if ($('.is-repeat-event').prop('checked')) {
      $('.event-date').prop('disabled', 'true' );
    }
    $('.is-repeat-event').change(function(){
        var d = this.checked ? 'true' : 'false';
        $('.event-date').prop('disabled', d );
    });
});

either part on it's own works but putting them together doesn't work (the .change event has no effect on the input).


Solution

  • That is beacause property disabled need to set to boolean true/false values. also you can trigger the event after binding it to see the relevant changes in page load:

    $('.is-repeat-event').change(function(){
       $('.event-date').prop('disabled', this.checked );
    }).change();