JQuery, how to disable or enable a <select> element with a checkbox when a page loads?

I have a simple function that disables / enables the select element when the checkbox is checked or unchecked. It works well. However, after submitting the form and checking the flag, it has already been checked (using PHP) the selection is not disabled until I double-click on this flag.

<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 tried a few things, however I'm not very good at jQuery yet ...

+3
source share
4 answers

Looks like you were almost there. Just a few syntax errors.

$("#worldcb").click(function(){
    var el = $("#worldSelect");
    if (el){
        el.removeAttr("disabled");
        if (this.checked){
            el.attr("disabled", "disabled");     
        }
    }
});        

Here's jsFiddle to demonstrate.

, ​​, .

if ($("#worldcb").is(":checked")){
    $("#worldSelect").attr("disabled", "disabled");
}
+6

toggleFunction , . autocomplete = "off" , ( ).

:

$(document).ready(function() {
    toggleSelection('#worldcb');
});
+1

, , disabled select html.

<select id="worldSelect" class="select" name="world" disabled></select>
0

, . toggleSelection , ,

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' ) );
});
0

All Articles