如何检查是否从两个不同的选择框中选择了两个特定选项

时间:2019-02-27 15:26:46

标签: javascript jquery select option

想法是使用两个选择框进行一些测试。因此,必须在以下每个选择框中选择一个选项。每个选择框中只有一个选项是正确的,其他选择-是错误的。

通过单击按钮,必须看到alert的答案是对还是错。

该循环实际上获取了页面上的所有选择框,但是代码不起作用。

如何用一个按钮检查是否从两个不同的选择框中选择了两个特定选项?

function check() {
  var rt = $(document).find('select');
  var count = rt.length;

  for (i = 0; i < count; i++) {
    $(rt[i]).change(function() {
      var val = $(this).children("option:selected").val();
      var right = $(this).children("option:selected").data('accept');
      if (val === right) {
        alert('right')
      } else {
        alert('wrong')
      }
    });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="country" id="first">
  <option>-</option>
  <option>United States</option>
  <option data-accept="India" value="right">India</option>
  <option>United Kingdom</option>
  <option>Russia</option>
</select>

<select class="country" id="second">
  <option>-</option>
  <option data-accept="United States" value="right">United States</option>
  <option>India</option>
  <option>United Kingdom</option>
  <option>Russia</option>
</select>

<button type="button" onclick="check()">check</button>

1 个答案:

答案 0 :(得分:0)

您无需在每次选择页面时都进行循环。这是一个有效的代码:

function check() {
  if (isSelectRight("#first") && isSelectRight("#second")) {
    alert("right");
  } else {
    alert("wrong");
  }
}

function isSelectRight(selectId) {
  const selected = $(selectId + " option:selected");
  return selected.attr("value") === "right";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="country" id="first">
  <option>-</option>
  <option>United States</option>
  <option data-accept="India" value="right">India</option>
  <option>United Kingdom</option>
  <option>Russia</option>
</select>

<select class="country" id="second">
  <option>-</option>
  <option data-accept="United States" value="right">United States</option>
  <option>India</option>
  <option>United Kingdom</option>
  <option>Russia</option>
</select>

<button type="button" onclick="check()">check</button>

基本上,您有一个函数selectisRight,该函数根据选项的selectId属性来检查传递的value的选定值是否正确。

您可以在所需的每个select上使用它。