【问题标题】:jQuery - Check If any select option is selectedjQuery - 检查是否选择了任何选择选项
【发布时间】:2013-03-17 12:21:41
【问题描述】:

基本上我有一个选择选项,它从数据库中提取所有“旅游名称”作为 $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>

【问题讨论】:

标签: jquery


【解决方案1】:

试试这个

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

【讨论】:

    【解决方案2】:

    可以通过测试select的value属性来判断一个option是否存在

    if($('#sel-destination-tour').val()){
        // do something
    } else {
        // do something else
    }
    

    【讨论】:

    • 如果选项的值为0怎么办?
    • 最好检查null,因为0 可能是一个有效的选项值,但在您的情况下它会评估为false。 IE。 $('#sel-destination-tour').val() != null.
    【解决方案3】:

    假设您有示例中显示的第一项,这将完成...

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

    【讨论】:

      【解决方案4】:

      检查val()(假设0没有值):

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

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

      【讨论】:

      • 只是评论:.val() 方法在某些情况下不起作用,我不知道正确的情况,它发生在 FF 中(尤其是change 以编程方式触发的大量选项)跨度>
      【解决方案5】:

      跟踪 select 的 change 事件并相应地做你的事情

      $(function(){
      
       $("#sel-destination-tour").change(function(){
      
       if($(this).val() !="0")
        {
          // logic goes here
        }
        else
        {
         // no option is selected
        }
      });
      
      });
      

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-11
          • 2014-03-28
          • 2019-02-25
          • 2015-07-05
          • 2011-01-24
          相关资源
          最近更新 更多