[jquery] Trigger change event <select> using jquery

is there anyway i could trigger a change event on select box on page load and select a particular option.

Also the function executed by adding the trigger after binding the function to the event.

I was trying to output something like this

<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>

$(function(){
    $('.check').trigger('change'); //This event will fire the change event. 
    $('.check').change(function(){
      var data= $(this).val();
      alert(data);            
    });
});

http://jsfiddle.net/v7QWd/1/

This question is related to jquery

The answer is


$('#edit_user_details').find('select').trigger('change');

It would change the select html tag drop-down item with id="edit_user_details".


Based on Mohamed23gharbi's answer:

function change(selector, value) {
    var sortBySelect = document.querySelector(selector);
    sortBySelect.value = value;
    sortBySelect.dispatchEvent(new Event("change"));
}

function click(selector) {
    var sortBySelect = document.querySelector(selector);
    sortBySelect.dispatchEvent(new Event("click"));
}

function test() {
    change("select#MySelect", 19);
    click("button#MyButton");
    click("a#MyLink");
}

In my case, where the elements were created by vue, this is the only way that works.


Give links in value of the option tag

<select size="1" name="links" onchange="window.location.href=this.value;">
   <option value="http://www.google.com">Google</option>
   <option value="http://www.yahoo.com">Yahoo</option>
</select>

If you want to do some checks then use this way

 <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
    <option value="">Select a Search Engine</option>        
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
</select>

<script>

   function functionToTriggerClick(link) {

     if(link != ''){
        window.location.href=link;
        }
    }  

</script>

Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

You can try below code to solve your problem:

By default, first option select: jQuery('.select').find('option')[0].selected=true;

Thanks, Ketan T


To select an option, use .val('value-of-the-option') on the select element. To trigger the change element, use .change() or .trigger('change').

The problems in your code are the comma instead of the dot in $('.check'),trigger('change'); and the fact that you call it before binding the event handler.