98

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

Boris Callens
  • 90,659
  • 85
  • 207
  • 305
Prasad
  • 58,881
  • 64
  • 151
  • 199
  • You might wanna put some more tag's such as javascript and jQuery to get this found more – xenon May 23 '09 at 19:05
  • http://stackoverflow.com/questions/31913370/set-or-change-thg-tortoisehg-branch-color/31913530#31913530 – LarryHuff Mar 26 '17 at 06:44

6 Answers6

202

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.

Christophe Eblé
  • 8,071
  • 3
  • 33
  • 32
12

Try this:

$(document).ready(function(event) {
    $('#countrylist').change(function(e){
         // put code here
     }).change();
});

Define the change event, and trigger it immediately. This ensures the event handler is defined before calling it.

Might be late to answer the original poster, but someone else might benefit from the shorthand notation, and this follows jQuery's chaining, etc

jquery chaining

mlnyc
  • 2,636
  • 2
  • 24
  • 29
9

Try this:

$('#id').change();

Works for me.

On one line together with setting the value: $('#id').val(16).change();

d.popov
  • 4,175
  • 1
  • 36
  • 47
3

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"

xenon
  • 1,435
  • 19
  • 35
  • I have cascading dropdowns: <%= Html.DropDownList("MyCountries", "---Select Country---")%> <%= Html.CascadingDropDownList("MyStates", "MyCountries")%> I can set the value of MyCountries as $("#MyCountries").val('<%= Model.CountryId %>'); in $(document).ready. But i m not able to set the value for state as it shows only one option "Select State", which should be filled on country onchange event as they are cascading dropdowns. This is actual issue. – Prasad May 23 '09 at 19:13
  • Still not sure what you are after. Are you trying to achieve a system whereby they select a country and it narrows the list down to the states in that country? If this is the case you will need to have an AJAX call to the server and send off the country selected and then return a liste of states in that country. – xenon May 23 '09 at 20:09
  • I have set USA as Country & Alabama as State which is a cascading dropdown, while adding the user profile. And when i come back to that page to Edit a field, i need Country and State to be populated with the values which i have set previously. I have no problem in adding the user profile, when i come back to the page to Edit, i am able to set the value for Country dropdown and in the state dropdown the values are not filled as it is cascading which gets fill on country value change event. For this i need to trigger the change event of country so that state gets fill and i can set state – Prasad May 24 '09 at 04:41
  • Why is this the case? You know what the country is at page load time thus you could render the correct select list of states with the correct state selected. When you change the country the list will get reloaded anyway. – xenon May 24 '09 at 11:21
2

alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.

<input type="dropdownlist" onchange="jqueryFunc()">

<script type="text/javascript">
$(function(){
    jqueryFunc(){
        //something goes here
    }
});
</script>

hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks

dave
  • 21
  • 1
  • This does not trigger the change event when the page first loads (as per OP's question) –  Jan 22 '15 at 10:54
1

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>
Domi
  • 22,151
  • 15
  • 92
  • 122