【问题标题】:Check if options is selected [duplicate]检查是否选择了选项[重复]
【发布时间】:2012-09-13 20:44:36
【问题描述】:

可能重复:
Check if option is selected with jQuery, if not select a default

我有这样的html:

<div id="somedivid">

<select class="someclass">
<!-- options -->
</select>

<select class="someclass">
<!-- options -->
</select>

</div>

如何检查两个选择框中的选项是否被选中?

编辑:我无法更改 html,所以这意味着我无法添加 id 来选择元素。

【问题讨论】:

  • 我所做的是将你的问题主题 + 'jquery' 写给谷歌,look what i found
  • @Tom 好吧,当只有一个选择元素时,您找到了解决方案。我知道该怎么做。

标签: jquery


【解决方案1】:

一个选择总是有一个选择。

但是假设你像这样输入一个空选项:

​<select id=select1>
    <option></option>
    <option>A</option>
    <option>B</option>
</select>​

你可以测试一下:

if ($('#select1').val() && $('#select2').val()) {
   // both have selection

编辑:如果你没有 id 或名字,你可以使用这个:

var allSelected = true:
$('#somedivid select').each(function() {
    if (!$(this).val()) {
       allSelected = false;
       break;
    }
});

【讨论】:

  • 是的,我知道这样做,但我的选择元素没有 id,只有两个元素相同的类。而且我无法更改 html。
  • 如果您没有 ID 或姓名,我编辑了一个解决方案。但是你必须定义什么意思是选择了某些东西(例如空选择)。
【解决方案2】:
<script type="text/javascript">
    $( function() { 
        $( '#somedivid > select' ).bind( 'change', function(){
            if( $( '#sel1').attr( 'value' ) != 'default' && $( '#sel1' ).attr( 'value' ) != 'default' ){
                //do something here.
            }
        });
    } );
</script>
<div id="somedivid">

    <select id="sel1">
        <option value="default" selected="selected"></option>
        <!-- options -->
    </select>

    <select id="sel2">
        <option value="default" selected="selected"></option>
        <!-- options -->
    </select>

</div>

【讨论】:

    【解决方案3】:

    考虑到两个选择框都有一些默认选项值="none"

    var isBothSelected=0;
    if($('#selectbox1 option:selected').val() =='none'){
        alert('Plase select the select1');
        isBothSelected=isBothSelected+1;
        //return false;
    }
    if($('#selectbox2 option:selected').val() =='none'){
        alert('Plase select the select2');
       isBothSelected=isBothSelected+1;
        // return false;
    }
    if(isBothSelected ==2){
      alert('Both are not selected')
    }
    

    【讨论】:

      【解决方案4】:

      试试这个

            var val=  $("#selectid option:selected").value();
                 if(val==="")
                     {
                alert("your code on not selected condition");
                 }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-05
        • 2014-03-16
        • 2014-03-28
        • 1970-01-01
        • 2013-03-17
        • 2019-02-25
        • 1970-01-01
        相关资源
        最近更新 更多