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 badges2 Answers
Reset to default 38You 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
版权声明:本文标题:javascript - EnableDisable Input based on selection (jQuery) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738008014a2048420.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论