I am trying to develop a JQuery script to change the state of a checkbox by setting the disabled attribute to true depending on the state of a different checkbox.
I have three checboxes – suspended, option1 and option2
Using the below code, thn clicking the suspended checkbox, the other two are disabled. If I uncheck the suspended box, they are then availble (disabled attr removed).
I would like to apply the same logic atpage load. My code is below:
(function( $ ) {
'use strict';
$( document ).ready(function() {
if( $('input[name="suspended"]').is(':checked')){
console.log( "Suspended is checked" );
$('input[name="option1"]' ).attr("disabled", true);
$('input[name="option2"]' ).attr("disabled", true);
}
else{
console.log( "Suspended is unchecked" );
$('input[name="option1"]' ).removeAttr("disabled");
$('input[name="option2"]' ).removeAttr("disabled");
}
$( 'input[name="suspended"]' ).change( function( e ){
e.preventDefault;
if ($(this).is(':checked')) {
$('input[name="option1"]' ).attr("disabled", true);
$('input[name="option2"]' ).attr("disabled", true);
}else {
$('input[name="option1"]' ).removeAttr("disabled");
$('input[name="option2"]' ).removeAttr("disabled");
}option2
} );
});
})( jQuery );
I have obviously solved the change state of click situation, but canno’t work out why it doesnt not also work on page load. I am able to get a concole.log message to display the state at page load, but chnage the state of the checboxes.
2
Answers
I can see that you like JQuery, but even in vanilla JavaScript it doesn’t have to be complicated. Instead of doing all the tests you can just give the
disabled
property the value of thechecked
property on the checkbox.I like using
<fieldset>
and it could make sense in this case, because you have more than one input element that you would like to disable.And here, the jQuery version:
@chrwahl has already provided some very good points in his answer. However, you could go even a little further by making the script shorter and at the same time applicable for a whole range of fieldsets:
The same can of course also be done in a Vanilla JavaScript way:
Admittedly, the vanilla version is slightly longer. I have chosen to use a delegated event listening here on the
form
element. This way even dynamically added fieldsets will respond to a change of their.suspended
checkbox, if available.