Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/Disable Input based on selection (jQuery)

<select name="state" class="select" id="state">
    <option value="something">Something</option>
    <option value="other">Other</option>
</select>

<input type="text" name="province" class="text" id="province" />

jQuery

$('#state').change(function () {
    if ($('#state Other:selected').text() == "Other"){
        $('#province').attr('disabled', false);
        alert(1);
    } else {
        alert(2);
    }
});

Doesn't seem to work. I must be doing something wrong.

like image 203
eozzy Avatar asked Jan 04 '11 18:01

eozzy


2 Answers

You should use .removeAttr('disabled') instead of .attr('disabled', false). Also you should cache your jQuery selectors.

Edit: Thought about this after the fact. You may want to "empty" the text that had been typed into the field if you are disabling it, so I added a .val(''), if you also wanted to hide it, you could add .hide() and .show() to the two cases.

I put together this fiddle to show you a working version:

var $state = $('#state'), $province = $('#province');
$state.change(function () {
    if ($state.val() == 'other') {
        $province.removeAttr('disabled');
    } else {
        $province.attr('disabled', 'disabled').val('');
    }
}).trigger('change'); // added trigger to calculate initial state

The .trigger('change') will "trigger" a change event, effectively running the function once while you bind it. This way, the #province will be either disabled / enabled based on the state selected at the time the code is run. Without it, the province would have been available even if the state isn't "other" unless you also added disabled='disabled' to the <input> tag in your html.

like image 163
gnarf Avatar answered Nov 04 '22 18:11

gnarf


You need to set "disabled" to true to actually disable something. For example, if you want to disable on "Other" and enable on everything else, then I suggest saying:

$('#state').change(function () {
    $("#province").attr("disabled", $("#state").val() == "other");
});

This uses $("#province").val() which is generally the preferred way to get the current value of the selected option from a dropdown in jQuery. The "disabled" attribute is set to true if the value is "other" and false otherwise.

like image 3
Eli Courtwright Avatar answered Nov 04 '22 19:11

Eli Courtwright