jQuery - 检查是否选择了任何选择选项

时间:2013-03-27 12:14:32

标签: jquery

基本上我有一个选择选项,可以将数据库中的所有“游览名称”作为$ touroptions。 $ touroptions可以包含1-20个值(选择选项)。

我需要做的是使用jQuery函数,如下所示: -

If (any option) #sel-destination-tour is selected {
//DO SOMETHING
}
ELSE {
//DO SOMETHING ELSE
}

我只是不确定如何做到这一点。

HTML

<select name="sel-destination-tour" id="sel-destination-tour" class="input-select-tour">

    <option value="0"></option>

    <?php echo $touroptions ?>

</select>

6 个答案:

答案 0 :(得分:28)

您可以通过测试select

的value属性来检查选项是否正确
if($('#sel-destination-tour').val()){
    // do something
} else {
    // do something else
}

答案 1 :(得分:4)

跟踪select的更改事件并相应地执行您的工作

$(function(){

 $("#sel-destination-tour").change(function(){

 if($(this).val() !="0")
  {
    // logic goes here
  }
  else
  {
   // no option is selected
  }
});

});

答案 2 :(得分:3)

试试这个

$('#sel-destination-tour').val() == ""){
    //nothing selected;
}else{
    //something selected;
}

答案 3 :(得分:1)

假设你有第一个项目,如你的例子所示,这样做......

if ($("#sel-destination-tour").val() != "0") {
    // nothing selected
} else {
    // something selected
}

答案 4 :(得分:0)

检查val()(假设0为无值):

if ($('#sel-destination-tour').val() != 0) {
   // has a value selected
} 
else {
   // does not have a value selected
}

示例 - http://jsfiddle.net/infernalbadger/RrtT7/

答案 5 :(得分:0)

在我的情况下,val()正在返回[]并以true的身份返回。所以我把它改成了:

if($('#sel-destination-tour').val()[0]){
    // do something
} else {
    // do something else
}
相关问题