检查是否选择了两个以上具有特定类的选项

时间:2015-02-25 11:31:26

标签: jquery

http://fiddle.jshell.net/oc48qztr/

我有四种选择,包括汽车模型和一架飞机。

我不知道如何检查是否选择了两个以上具有特定类的选项。

选择两辆以上的车后,应该显示警报。

$('button').click(function() {
  if (($('select[name*="select-model"] option:selected').is('.car').length > 2)) {
    alert("You can't choose more than two cars!");
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="select-model">
  <option value="0"></option>
  <option class="boe airplane" value="0">Boeing - This is not a car!</option>
  <option class="vol car" value="0">Volkswagen</option>
  <option class="kia car" value="0">KIA</option>
  <option class="bwm car" value="0">BMW</option>
  <option class="mer car" value="0">Mercedes</option>
</select>
<br>
<select name="select-model">
  <option value="0"></option>
  <option class="boe airplane" value="0">Boeing - This is not a car!</option>
  <option class="vol car" value="0">Volkswagen</option>
  <option class="kia car" value="0">KIA</option>
  <option class="bwm car" value="0">BMW</option>
  <option class="mer car" value="0">Mercedes</option>
</select>
<br>
<select name="select-model">
  <option value="0"></option>
  <option class="boe airplane" value="0">Boeing - This is not a car!</option>
  <option class="vol car" value="0">Volkswagen</option>
  <option class="kia car" value="0">KIA</option>
  <option class="bwm car" value="0">BMW</option>
  <option class="mer car" value="0">Mercedes</option>
</select>
<br>
<select name="select-model">
  <option value="0"></option>
  <option class="boe airplane" value="0">Boeing - This is not a car!</option>
  <option class="vol car" value="0">Volkswagen</option>
  <option class="kia car" value="0">KIA</option>
  <option class="bwm car" value="0">BMW</option>
  <option class="mer car" value="0">Mercedes</option>
</select>
<br>
<br>
<button type="submit">Click</button>

2 个答案:

答案 0 :(得分:2)

试试这个:

$('button').click(function () {
    var carCount = $('option.car:selected').length;
    var planeCount = $('option.airplane:selected').length;
    console.log("car", carCount, "else", planeCount)
});

演示:http://fiddle.jshell.net/oc48qztr/1/

根据这些值,您可以实现您的逻辑。

答案 1 :(得分:0)

这是你需要的 -

演示 - http://fiddle.jshell.net/oc48qztr/5/

$('button').click(function() {

    if (($('select option:selected[class*="car"]').length > 2)) {

        alert("You can't choose more than two cars!");
    }

});