Disable select element when checkbox is checked using jQuery

I want to create a script that will disable the selection form element when checking the desired checkbox. Since there will be more times I will use this, I would like to make it as a function that takes the target identifier of the choice as an argument. The problem is that this function does not work when I pass id as an argument. On the contrary, it works with a hard-coded identifier.

<select id="worldSelect" class="select" name="world">
<input id="worldcb" type="checkbox" checked="yes" value="any" name="world">

function toggleSelection(id){
    var el = '#' + id;
    if (this.checked) {
        $(el).attr('disabled', 'disabled');
    } else {
        $(el).removeAttr('disabled');
    }
}

$(function() {
    toggleSelection('worldSelect');
    $('#worldcb').click(toggleSelection);
});
0
source share
2 answers

You cannot call the same function twice and expect the function to remember the id variable.

However, you can do something like this:

function toggleSelection(e){
    var el = '#' + e.data;
    console.log(arguments);
    if (this.checked) {
        $(el).attr('disabled', 'disabled');
    } else {
        $(el).removeAttr('disabled');
    }
}

$(function() {
    $('#worldcb').click('worldSelect', toggleSelection);
});​

Fiddle: http://jsfiddle.net/4ZBne/1/

+2
source

What about:

$('#worldcb').click(function() {
    toggleSelection('worldSelect', $(this).is(':checked'));
});

function toggleSelection(sel, chk) {
    $('#' + sel).attr('disabled', chk);
}​

jsFiddle.

toggleSelection() , sel - chk, .

+1