Search code examples
javascriptjquerydomdhtml

jQuery: How to hook and identify drop-down selection


I have a list of rows containing selects:

<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>

I want to have unified jQuery code like:

$(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...'
}

Solution

  • You can use *in your selector this selects all elements that have the specified attribute with a value containing a given substring and then simply use attr('id')) and .val() to get values from select-box .

    Demo Code :

    $("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>