【问题标题】:How to check whether two particular options from two different select boxes are selected如何检查是否选择了来自两个不同选择框的两个特定选项
【发布时间】:2019-07-21 09:03:23
【问题描述】:

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

通过单击按钮,您必须看到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>

【问题讨论】:

    标签: javascript jquery select option


    【解决方案1】:

    您不需要在页面的每个选择上循环。这是一个有效的代码:

    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,它根据选项的value 属性检查传递的selectId 的选定值是否正确。

    您可以在每个您想要的select 上使用它。

    【讨论】:

      猜你喜欢
      • 2023-02-24
      • 2021-10-20
      • 1970-01-01
      • 2019-02-25
      • 2011-08-09
      • 2013-03-17
      • 2014-03-28
      • 1970-01-01
      相关资源
      最近更新 更多