views:

1488

answers:

2

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

A: 

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 ahve 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
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
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
Prasad
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
+3  A: 

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');
});

More information here.

SleepyCod