patternjavascriptMinor
Function that enables fields based on checkbox state
Viewed 0 times
fieldsfunctioncheckboxthatstatebasedenables
Problem
I have simple code that just has to check if a checkbox is checked and if so enable some fields that, by default, should be disabled.
I have written the next code which I know can be severely improved. Could anyone tell me how? I tried getting the siblings of the checkbox also but that just caused some trouble.
I have written the next code which I know can be severely improved. Could anyone tell me how? I tried getting the siblings of the checkbox also but that just caused some trouble.
$(function(){
$('#amount').attr('disabled','disabled');
$('#period').attr('disabled','disabled');
$('#key').attr('disabled','disabled');
$('#api').change(function(){
if($('#apiEnabled').is(':checked')){
$('#amount').attr('disabled','');
$('#period').attr('disabled','');
$('#key').attr('disabled','');
}else{
$('#amount').attr('disabled','disabled');
$('#period').attr('disabled','disabled');
$('#key').attr('disabled','disabled');
}
});
});Solution
It's difficult to answer accurately without seeing your markup, but maybe you can use a multiple selector to alleviate code redundancy. You can also use prop() to enable or disable your elements more easily:
$(function() {
var $elements = $("#amount, #period, #key");
$elements.prop("disabled", true);
$("#api").change(function() {
$elements.prop("disabled", !$("#apiEnabled").is(":checked"));
});
});Code Snippets
$(function() {
var $elements = $("#amount, #period, #key");
$elements.prop("disabled", true);
$("#api").change(function() {
$elements.prop("disabled", !$("#apiEnabled").is(":checked"));
});
});Context
StackExchange Code Review Q#4787, answer score: 2
Revisions (0)
No revisions yet.