admin管理员组

文章数量:1178592

<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.

<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.

Share Improve this question asked Jan 4, 2011 at 18:35 eozzyeozzy 68.7k108 gold badges284 silver badges447 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 38

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.

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.

本文标签: javascriptEnableDisable Input based on selection (jQuery)Stack Overflow