jqueryselectdropdownsimulate

on button click fire or simulate select dropdown list show


I am looking for a way to open a select options (like if we click on a select) when I click on a button. like this example : enter image description here

the HTML code is here :

<select id="sel1">
    <option value="">Please select an option</option>
    <option value="1">Val1</option>
    <option value="2">Val2</option>
    <option value="3">Val3</option>
</select>
<button id="btn">fire</button>

https://jsfiddle.net/stefchrif/2vz7fog3


Solution

  • You need to use click event then find option with value "option[value="2"]" and then set prop selected to true

    https://api.jquery.com/prop/

    // click on button
    $('#btn').click( function() {
      //$('#sel1').find('option[value="2"]').prop('selected', true);
      var size = $('#sel1 option').length;
      if (size != $("#sel1").prop('size')) {
          $("#sel1").prop('size', size);
      } else {
          $("#sel1").prop('size', 1);
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="sel1">
        <option value="">Please select an option</option>
        <option value="1">Val1</option>
        <option value="2">Val2</option>
        <option value="3">Val3</option>
    </select>
    <button id="btn">fire</button>