jQuery - 检查是否选择了任何选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15658528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Check If any select option is selected
提问by nsilva
Basically I have a select option which pulls all the 'Tour Names' from a database as $touroptions. $touroptions can contain anything from 1-20 values (select options).
基本上我有一个选择选项,它从数据库中提取所有“旅游名称”作为 $touroptions。$touroptions 可以包含 1-20 个值(选择选项)。
What I need to do is have a jQuery function to do as follows so:-
我需要做的是有一个 jQuery 函数,如下所示:-
If (any option) #sel-destination-tour is selected {
//DO SOMETHING
}
ELSE {
//DO SOMETHING ELSE
}
I'm just not sure how I could do this.
我只是不确定我怎么能做到这一点。
HTML
HTML
<select name="sel-destination-tour" id="sel-destination-tour" class="input-select-tour">
<option value="0"></option>
<?php echo $touroptions ?>
</select>
回答by Arun P Johny
You can check whether a option by testing the value attribute of the select
您可以通过测试 select 的 value 属性来检查一个选项
if($('#sel-destination-tour').val()){
// do something
} else {
// do something else
}
回答by K D
track the change event of select and do your stuffs accordingly
跟踪选择的更改事件并相应地做你的事情
$(function(){
$("#sel-destination-tour").change(function(){
if($(this).val() !="0")
{
// logic goes here
}
else
{
// no option is selected
}
});
});
回答by bipen
try this
尝试这个
$('#sel-destination-tour').val() == ""){
//nothing selected;
}else{
//something selected;
}
回答by Reinstate Monica Cellio
Assuming that you have the first item as shown in your example, this will do it...
假设您拥有示例中所示的第一项,这将完成...
if ($("#sel-destination-tour").val() != "0") {
// nothing selected
} else {
// something selected
}
回答by Richard Dalton
Check the val()
(assuming 0 is no value):
检查val()
(假设 0 没有值):
if ($('#sel-destination-tour').val() != 0) {
// has a value selected
}
else {
// does not have a value selected
}
回答by Adam Grey
In my situation val()
was returning []
and coming up as true
. So I changed it to:
在我的情况下val()
,返回[]
并出现为true
. 所以我把它改成:
if($('#sel-destination-tour').val()[0]){
// do something
} else {
// do something else
}