我有一个输入字段:
<input id="count" name="count" min="1" value="1" type="number" />
和一个选择框:
<select id="select">
<option>nothing selected</option>
<option data-number="4">four (4)</option>
<option data-number="5">five (5)</option>
<option data-number="6">six (6)</option>
</select>
我想实现以下目标:
如果#count
的输入值高于#select
的data-number
,则禁用此选项(例如:如果#count
的输入值高于 "5"
,然后使用 data-number="5"
禁用该选项。
我还希望自动选择 #select
选项,其中 #count
的值最适合(例如:对于输入值 "3"
自动选择数据编号“4”
的选项,对于输入值“4”
选择数据编号“4”
的选项code>,对于输入值“5”
,选择带有数据编号“5”
的选项)
这是我尝试解决它的方法,但它不起作用:
$(function(){
$('input').change(function(){
if($('#count').val() > $('#select').data(number)) {
$('#select option').attr('disabled', true);
}
else {
$('#select option').attr('disabled', false);
}
if ($('#select').data(number) == Math.min($('#select').data(number) - $('#count').val()){
$('#select option').attr('selected', true);
}
});
}
这是 fiddle :https://jsfiddle.net/dh1ak18t/
最佳答案
检查下面的代码和 link
$('input').change(function(){
if($('#count').val() > $('#select option:last-child()').data("number")) {
$('#select option[data-number="6"]').attr('disabled', 'disabled');
}
else {
$('#select option[data-number="6"]').removeAttr('disabled');
$('#select option[data-number="'+$('#count').val()+'"]').attr('selected', 'selected');
}
});
关于jquery - 如何使用 jquery 禁用或选择选择框中的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966896/