检查是否有任何未选中的DropDownList

时间:2018-04-04 00:53:36

标签: javascript jquery

假设有3个下拉列表,如何检查是否有未选择的下拉列表?

var unselected = $('.dropdown:selected').lenght;

if(unselected > 0){
alert('At least one dd is not selected')
}

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要检查是否有一些下拉列表未被选中,除了已禁用的选项外,还有一个可用选项。

你可以这样做:



function checkSelected(){
  $('select').each(function(){
    console.log($('option',this).not(':disabled').is(':selected') ? 'selected' : 'no selection for ' + $(this).attr('id') )
  })
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1">
  <option disabled selected value> -- Please select -- </option>
  <option value="1">A Test 1</option>
  <option value="2">A Test 2</option>
</select>
<select id="select2">
  <option disabled selected value> -- Please select -- </option>
  <option value="1">B Test 1</option>
  <option value="2">B Test 2</option>
</select>
<select id="select3">
  <option disabled selected value> -- Please select -- </option>
  <option value="1">C Test 1</option>
  <option value="2">C Test 2</option>
</select>

<button onclick="checkSelected()">Click me!</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

来自@Sphinx的修改代码。显示&#34;未选中&#34;的计数垮台和&#34;总计&#34;沮丧。

&#13;
&#13;
function checkSelected(){
      var i = 0;
      var total =  $('.dropdown').length;  
      $('.dropdown').each(function(){
            //console.log($(this).attr('id'));  
            if(!$('option',this).not(':disabled').is(':selected')) i++;
            // console.log(i + " dropdowns are NOT selected"); 
      });
      console.log(i + " of " + total +" dropdowns are NOT selected");
    }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="select1" class="dropdown">
      <option disabled selected value> -- Please select -- </option>
      <option value="1">A Test 1</option>
      <option value="2">A Test 2</option>
    </select>
    <select id="select2" class="dropdown">
      <option disabled selected value> -- Please select -- </option>
      <option value="1">B Test 1</option>
      <option value="2">B Test 2</option>
    </select>
    <select id="select3" class="dropdown">
      <option disabled selected value> -- Please select -- </option>
      <option value="1">C Test 1</option>
      <option value="2">C Test 2</option>
    </select>

    <button onclick="checkSelected()">Click me!</button>
&#13;
&#13;
&#13;