i'm having checkboxes , text inputs. text inputs disabled when pages loads. if checkbox checked, corresponding input should fillable. here's current code
for reason can't seem right, i'm pretty new js , jquery. when click checkboxes, nothing happens, , when load page 6 times text "false"
var c1 = $('#check1'); var c2 = $('#check2'); var c3 = $('#check3'); var f1 = $('#field1'); var f2 = $('#field2'); var f3 = $('#field3'); $(function() { enable_cb(c1, f1); enable_cb(c2, f2); enable_cb(c3, f3); c1.click(enable_cb(c1, f1)); c2.click(enable_cb(c2, f2)); c3.click(enable_cb(c3, f3)); }); function enable_cb(checkbox, field) { if (checkbox.checked) { console.log('if'); field.removeattr("disabled"); } else { console.log('else'); field.attr("disabled", true); } }
here's piece of html, other parts same one:
<div class="form-group" > <label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect customcheckbox" for="check1"> {{ form::checkbox('check', 1, null, ['class' => 'mdl-checkbox__input', 'id' => 'check1']) }} <span class="mdl-checkbox__label">test</span> </label> </div> <div class="form-group" > <label for="field1">test<br></label> <select id="field1" name="field1" disabled class="searchselect searchselectstyle"> </select> @if ($errors->has('field1')) <span class="help-block"> <strong>{{ $errors->first('field1') }}</strong> </span> @endif </div>
you have several issues.
- you should use
change
event when dealing checkboxes people navigate keyboard can use them. - you should provide anonymous function event handler. current code executing
enable_cb()
function , ignoring further events. - the
checkbox
parameter passed function jquery object has nochecked
property. should useis(':checked')
instead. - you should use
prop()
onattr()
,removeattr()
possible.
try this:
$(function() { enable_cb(c1, f1); enable_cb(c2, f2); enable_cb(c3, f3); c1.change(function() { enable_cb(c1, f1) }); c2.change(function() { enable_cb(c2, f2) }); c3.change(function() { enable_cb(c3, f3) }); }); function enable_cb(checkbox, field) { if (checkbox.is(':checked')) { console.log('if'); field.prop("disabled", false); } else { console.log('else'); field.prop("disabled", true); } }
that said, should dry code reduce repetition. how depends on html structure, here's example.
<div class="checkbox-group"> <input type="checkbox" id="check" /> <input type="text" id="subcomplex"/> </div> <div class="checkbox-group"> <input type="checkbox" id="yearlymanagermaintainancedayscheck" /> <input type="text" id="yearlymanagermaintainancedays" /> </div> <div class="checkbox-group"> <input type="checkbox" id="yearlysuppliermaintainancedayscheck" /> <input type="text" id="yearlysuppliermaintainancedays" /> </div>
$('.checkbox-group :checkbox').change(function() { $(this).siblings('input').prop('disabled', !this.checked); }).change();
note how simpler code latter version, , how js require no updates or maintenance no matter how many input
elements add html.
Comments
Post a Comment