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

2 Answers 2

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.

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

3 Comments

Thank you! Could you explain the trigger a little more. Don't really understand.
@WmasterJ - Added a bit of an explanation
What if i want to use the same script for multiple select? Is there a generic one? Thanks
3

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.

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.