Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, how to disable or enable <select> element with checkbox upon page loading?

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...

like image 218
Paweł Duda Avatar asked May 09 '12 21:05

Paweł Duda


3 Answers

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");
}
like image 142
James Johnson Avatar answered Oct 14 '22 07:10

James Johnson


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');
});
like image 33
Malyo Avatar answered Oct 14 '22 05:10

Malyo


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' ) );
});
like image 21
gotofritz Avatar answered Oct 14 '22 05:10

gotofritz