Trigger change event of dropdown

Viewed 201682

I want to trigger the change event of dropdown in $(document).ready using jquery.

I have a cascading dropdown for country and state in user details page. how can i set the value (which is taken from DB based on the user id) for country and state in MVC with C#.

6 Answers

I don't know that much JQuery but I've heard it allows to fire native events with this syntax.

$(document).ready(function(){

    $('#countrylist').change(function(e){
       // Your event handler
    });

    // And now fire change event when the DOM is ready
    $('#countrylist').trigger('change');
});

You must declare the change event handler before calling trigger() or change() otherwise it won't be fired. Thanks for the mention @LenielMacaferi.

More information here.

If you are trying to have linked drop downs, the best way to do it is to have a script that returns the a prebuilt select box and an AJAX call that requests it.

Here is the documentation for jQuery's Ajax method if you need it.

$(document).ready(function(){

    $('#countrylist').change(function(e){
        $this = $(e.target);
        $.ajax({
            type: "POST",
            url: "scriptname.asp", // Don't know asp/asp.net at all so you will have to do this bit
            data: { country: $this.val() },
            success:function(data){
                $('#stateBoxHook').html(data);
            }
        });
    });

});

Then have a span around your state select box with the id of "stateBoxHook"

For some reason, the other jQuery solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.

Luckily, this Vanilla JS solution (the triggerChangeEvent function) did work:

/**
  * Trigger a `change` event on given drop down option element.
  * WARNING: only works if not already selected.
  * @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258
  */
function triggerChangeEvent(option) {
  // set selected property
  option.selected = true;
  
  // raise event on parent <select> element
  if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    option.parentNode.dispatchEvent(evt);
  }
  else {
    option.parentNode.fireEvent("onchange");
  }
}

// ################################################
// Setup our test case
// ################################################

(function setup() {
  const sel = document.querySelector('#fruit');
  sel.onchange = () => {
    document.querySelector('#result').textContent = sel.value;
  };
})();

function runTest() {
  const sel = document.querySelector('#selector').value;
  const optionEl = document.querySelector(sel);
  triggerChangeEvent(optionEl);
}
<select id="fruit">
  <option value="">(select a fruit)</option>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="pineapple">Pineapple</option>
</select>

<p>
  You have selected: <b id="result"></b>
</p>
<p>
  <input id="selector" placeholder="selector" value="option[value='banana']">
  <button onclick="runTest()">Trigger select!</button>
</p>

Related