jQuery:如何勾选和识别下拉选择

jQuery: How to hook and identify drop-down selection

我有一个包含选择的行列表:

<ul>
  {% for select in selects %}
    <li>
      <select id="select-{{ select.id }}">
        <option selected disabled>Select value...</option>
        {% for value in values %}
          <option value="{{ value.id }}">{{ value.name }}</option>
        {% endfor %}
      </select>
    </li>
  {% endfor %}
</ul>

我想要统一的 jQuery 代码,例如:

$(something).onSelect(function(value) {
  // use this.id as select id;
  // use value as selected value;
  return false; // don't change selected item, leave it as 'Select value...'
}

您可以在您的 select 或此 select 中使用 * 所有具有指定属性且值包含给定子字符串的元素,然后只需使用 attr('id')).val() 从 select-box 获取值。

演示代码 :

$("select[id*='select']").on("change", function(value) {
  console.log($(this).attr('id')) //get id
  console.log($(this).val()) //get value
  //some condition 
  //to set first value
  //$(this).val('Select value...') //or
  //$("#"+$(this).attr('id')).val('Select value...')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>

  <li>
    <select id="select-1">
      <option selected disabled>Select value...</option>
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
  </li>
  <li>
    <select id="select-2">
      <option selected disabled>Select value...</option>
      <option value="1">1</option>
      <option value="2">2</option>

    </select>
  </li>
  <li>
    <select id="select-3">
      <option selected disabled>Select value...</option>
      <option value="1">1</option>
      <option value="2">2</option>

    </select>
  </li>

</ul>