I have a simple function which disables/enables select element when checkbox is checked/unchecked. It works well. However, once the form is submitted and the checkbox loads already checked (with help of PHP), selection is not disabled until I click on the checkbox twice.
<select id="worldSelect" class="select" name="world">
<input id="worldcb" type="checkbox" checked="yes" value="any" name="world">
any world
function toggleSelection(element){
if (this.checked) {
$(element.data).attr('disabled', 'disabled');
} else {
$(element.data).removeAttr('disabled');
}
}
$(function() {
$('#worldcb').click('#worldSelect', toggleSelection);
});
I have tried several things, however I'm not any good with jQuery so far...
Looks like you were almost there. Just a couple of syntax errors.
$("#worldcb").click(function(){
var el = $("#worldSelect");
if (el){
el.removeAttr("disabled");
if (this.checked){
el.attr("disabled", "disabled");
}
}
});
Here's a jsFiddle to demonstrate.
As for retaining the disabled state when the page is posted back, you just need to run some logic when the page is loaded.
if ($("#worldcb").is(":checked")){
$("#worldSelect").attr("disabled", "disabled");
}
Well easiest way would be asigning your toggleFunction to document ready, so every time page loads it will check that checkbox status, and correct displaying of the select. You can give autocomplete="off" atribute to specific form field, to make it not cache (so the checkbox will be turned off after page refresh).
Example:
$(document).ready(function() {
toggleSelection('#worldcb');
});
Well you need to sync the two on load. Also change toggleSelection so that it works both called as an event handler or standalone
function toggleSelection( element, scope ){
scope = scope || this;
if (scope.checked) {
$(element.data).attr('disabled', 'disabled');
} else {
$(element.data).removeAttr('disabled');
}
}
$(function() {
$('#worldcb').click('#worldSelect', toggleSelection);
toggleSelection( { data : '#worldSelect' }, document.querySelector( '#worldcb' ) );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With