0

I want to make a script which will disable a select form element upon checking desired checkbox. Since there will be more times I will use this, I wanted to make it as a function which takes target selection id as an argument. The problem is, this function doesn't work when I'm passing the id as argument. On the contrary, it seems to work with hard-coded id.

<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);
});
3
  • Are you suggesting that toggleSelection('worldSelect'); works, but $('#worldcb').click(toggleSelection); doesn't? Commented May 9, 2012 at 20:33
  • Hiya, try this short and nice! jsfiddle.net/RqGnF let me know if you like it I can set this as answer, hope this helps, have a nice one, cheerios! Commented May 9, 2012 at 20:36
  • No, he is saying that replacing var el = '#' + id; with var el = '#' + 'worldSelect'; works. Then you also wouldn't need the line toggleSelection('worldSelect'); Commented May 9, 2012 at 20:38

2 Answers 2

2

You can't invoke the same function twice and expect the function to remember the id variable.

However you could 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/

Sign up to request clarification or add additional context in comments.

3 Comments

$(el).prop('disabled', this.checked ) a shorter way to write it. +1 for actually understanding the problem and what the OP intended. jsfiddle.net/4ZBne/2
@Interstellar_Coder I actually know almost nothing about jQuery. I just looked the click function up.
Tyilo, in that case you deserve more than a +1 :-)
1

How about:

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

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

jsFiddle example.

The toggleSelection() function takes two arguments, sel - the ID of the select box and chk, the checkbox to use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.