简体   繁体   中英

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).

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();

Try using trigger() :

 $(function() { $('.is-repeat-event').on('change', function(e) { $('.event-date').prop('disabled', this.checked); }).trigger('change'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div> <label>Repeat <input type='checkbox' class="is-repeat-event" checked='' /> </label> </div> Event Date <input type='date' class="event-date" value="2015-07-12" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM