Ad

JQuery Checkbox Auto Disable And Re-enable

- 1 answer

I have my HTML code and my JavaScript code like this (I'm using jQuery)

HTML :

<input type="checkbox" name="type" value="program" id="box-1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
    <option value="c">C/C++</option>
    <option value="vb">VB</option>
    <option value="cs">C#</option>
</select><br /><br />

<input type="checkbox" name="type" value="web" id="box-2" /> Web Development
<select name="lang-2" id="select-2" disabled>
    <option value="asp">ASP</option>
    <option value="php">PHP</option>
    <option value="ror">Ruby on Rails</option>
</select><br /><br />

JavaScript (jQuery) :

$(document).ready(function(){
    var x;
    $("#box-" + x).click(function(){
        var $this = $(this);
        if ($this.is(":checked")) {
            $("#select-" + x).prop('disabled', false);
        } else {
            $("#select-" + x).prop('disabled', true);
        }
    });
});

And I want when I checked the programming checkbox, the programming select option (beside the checkbox) is enable. As well as when I checked the web dev checkbox, the web dev select option is enable. But my code doesn't work. Can anybody help me?

Ad

Answer

You're better off using classes in stead of ID's with a random number. I would give all my checkboxes the class "box" and the id 1, 2, 3 and so on.

Also, I think $this doesn't work. It has to be $(this).

Then your code would look like (working example):

$(document).ready(function(){
    $('.box').click(function(){
        var x= $(this).attr("id");
        if ($(this).is(":checked")) {
            $("#select-" + x).prop('disabled', false);
        } else {
            $("#select-" + x).prop('disabled', true);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="type" value="program" class="box" id="1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
    <option value="c">C/C++</option>
    <option value="vb">VB</option>
    <option value="cs">C#</option>
</select><br /><br />

<input type="checkbox" name="type" value="web" class="box" id="2" /> Web Development
<select name="lang-2" id="select-2" disabled>
    <option value="asp">ASP</option>
    <option value="php">PHP</option>
    <option value="ror">Ruby on Rails</option>
</select><br /><br />

Ad
source: stackoverflow.com
Ad