How can I simulate a click on a specific option in the drop-down list?

For example, there are buttons:

<a class="but-1">butt</a> <a class="but-2">butt</a> 

And the list:

 <select> <option value="val1">value1</option> <option value="val2">value2</option> </select> 

How to make it so that when you press the .but-1 button, pressing is simulated, like using the val1 option?

  • Do you need to play exactly the click? or just select val1 in the list, as if it were selected manually? - PashaPash
  • As if it were selected manually, by mouse. Those. clicked on the list, the elements fell out, clicked on the option with the mouse. something like that - Vadim Avlochinsky
  • Do you want to get it? - jsfiddle.net/soledar10/vun3j8Lp - soledar10

2 answers 2

You can do it like this:

  1. add the data-select attribute to the button, which will contain the value item to select;
  2. hang event handler on the block with buttons;
  3. in the handler, we look at whether the element that called it has the data-select attribute, if there is, then select the item in the drop-down list;
  4. call the change event.

The complete jsFiddle example:

 document.getElementsByClassName('btn-group')[0].addEventListener('click', function(evt) { var elem = evt.target; if (elem.hasAttribute('data-select')) { document.getElementById('select').value = elem.getAttribute('data-select'); var elem = document.getElementById('select'); var event = new Event('change'); elem.dispatchEvent(event); } }, false); 

When setting "manually", after changing the value, read the .value fields in select , the change event occurs. Therefore, after programmatically selecting the desired item in the list, you need to trigger this event. I described the solution in pure JS, all this can be easily rewritten using jQuery, then the event will be called like this:

 $(select).trigger('change'); 

    In a more or less organized way, it looks like this.

     $(document).ready(function() { $('.btns').on('click', 'a[data-option]', function() { option = $(this).data('option'); $('.select option[value="' + option + '"]').prop('selected', true); return false }); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="btns"> <a href="#" data-option="value1">Кнопка 1</a> <a href="#" data-option="value2">Кнопка 2</a> </div> <select class="select"> <option value="">Выбери меня</option> <option value="value1">Выбор 1</option> <option value="value2">Выбор 2</option> </select> 

    In your case, you may have enough for understanding and the line

      $('.select option[value="' + option + '"]').prop('selected', true); 
    • Yes, it works, thanks. but only value in changes. My function is triggered when a live button is clicked on an option, and if I use the solution of an "inanimate" choice, the function does not work - Vadim Aulochinsky
    • To be honest, I do not understand. What does "not live" choice mean? - xaja