[英]Enable/disable button depending on whether an input in a text box is in a select box
I have nearly finished writing this code: http://jsfiddle.net/2Jkk9/11/ 我几乎完成了这段代码的编写: http : //jsfiddle.net/2Jkk9/11/
but I can't figure out how to search the select box for the value in my text box and enable/disabled the button accordingly. 但我不知道如何在选择框中搜索文本框中的值并相应地启用/禁用按钮。
That's probably enough explanation.. the code explains all... 可能就足够了。代码解释了所有...
Thank you :). 谢谢 :)。
EDIT Here's my original code from jsfiddle: 编辑这是我来自jsfiddle的原始代码:
<select id="myselect">
<option>apple</option>
<option>banana</option>
<option>pear</option>
</select>
<br><br>
<input id="filter" type="text"/>
and 和
$(function() {
$('#filter').keyup(function() {
// if select box contains input then
// $('#mybtn').attr(disabled, 'disabled');
//}
//else {
// $('#mybtn').removeAttr('disabled');
//}
});
});
This should do what you want by filtering the options for ones matching the text and checking the length: 这应该通过过滤与文本匹配的选项并检查长度来完成所需的操作:
$('#filter').keyup(function() {
var text = $(this).val();
if ($('#myselect option').filter(function() {
return $(this).text() === text;
}).length) {
$('#mybtn').attr('disabled', 'disabled');
}
else {
$('#mybtn').removeAttr('disabled');
}
});
http://jsfiddle.net/infernalbadger/2Jkk9/16/ http://jsfiddle.net/infernalbadger/2Jkk9/16/
Use each()
to loop through to traverse your list and get value by .val()
使用each()
循环遍历您的列表并通过.val()
获取值
check modified code. 检查修改后的代码。
(function() {
$('#filter').keyup(function() {
$('#myselect option').each(function(){
if($(this).val() == $('#filter').val())
{
$('#mybtn').attr('disabled', 'disabled');
alert('hello');
}
else
{
$('#mybtn').removeAttr('disabled');
}
});
// if select box contains input then
// $('#mybtn').attr(disabled, 'disabled');
//}
//else {
// $('#mybtn').removeAttr('disabled');
//}
});
$(function() {
$('#filter').keyup(function() {
if($("#filter").val().split($("#myselect").val()).length > 1) {
$('#mybtn').removeAttr('disabled');
}
else {
$('#mybtn').attr('disabled', 'disabled');
}
});
});
this works if the filter contains the selected value, not only when the same. 如果过滤器包含选定的值,则不仅在相同时,它也起作用。
What about: give your options a value like: 怎么样:给您的选项一个值,例如:
<select>
<option value="1"></option>
</select>
$('#myselect').change(function () {
if ($(this).val() == "1") {
//do this
} else {
//do this
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.