jeudi 2 avril 2015

Determine checked box status on page load, disable closest input if checked

I have a form which promts users for input, however each field has an 'unavailable' checkbox incase data is not available.


Note the checkboxes are of the form:



<input id="un_123" class="unavailable" type="checkbox" name="un_123" value="unavailable">


If users select this, I have the following jquery to disable the field



$(document).ready(function(){
$('.unavailable').change(function() {
var i = $(this).prev('input'),
d = i.attr('disabled');
i.attr('disabled', !d);
i.val('Unavailable');
});
});


Which toggles the field as disabled with the check box.


However when the page loads the state of the checkbox is preserved (if checked this is recorded in a table and referenced on page load to load it as checked or not checked, however the field is obviously loaded as not disabled.


I have multiple instances of these field / checkbox pairings on a page, so I want to be able to check on page load which are loaded checked, and then disable the field closest to each of them.


But without the .change trigger and relying on this I'm not sure how to proceed?


I've tried:



$(document).ready(function(){
if($('.unavailable').is(':checked')){
var i = $('.unavailable').prev('input'),
d = i.attr('disabled');
i.attr('disabled', !d);
i.val('Unavailable');
}
});


But it didn't work (page loaded with all inputs next to checkboxes disabled)





Aucun commentaire:

Enregistrer un commentaire