How to print the first item from the drop-down list when changing?

I have this function:

function LoadRegions() { var region = $('#RegionID'); var url = "/Account/GetRegions"; $.getJSON(url, { countryId: $('#CountryID').val() }, function (response) { // clear and add default (null) option //region.empty().append($('<option></option>').val('').text('Please select')); for (var i = 0; i < response.length; i++) { region.append($('<option></option>').val(response[i].Id).text(response[i].Name)); } }); } 

When the user selects countrie, I call this function, but I want to display the first item from this list at startup ... With this line, I get "Please select", but I need the first item from the list:

  region.empty().append($('<option></option>').val('').text('Please select')); 

If I comment on this line, I will get empty ... any help?

+5
source share
3 answers

I believe the problem could be with chain issues. See the documentation for end () .

empty() and append() executed in the same chain. This can sometimes cause problems due to the chaining algorithm. The documentation has a good description of the problem.

This may solve your problem.

 $.getJSON(url, { countryId: $('#CountryID').val() }, function(response) { // clear and add default (null) option region .empty() .end() .append($('<option>', { value: '', text: 'Please select' })); $.each(response, function(key, tocken) { region.append($('<option>', { value: tocken["Id"], text: tocken["Name"] })); }); }); 
+2
source

you need to set the selected attribute in the parameter tag to set this parameter as selected. To do this, you need to modify your for loop as follows:

 for (var i = 0; i < response.length; i++) { if(i==0) region.append($('<option selected></option>').val(response[i].Id).text(response[i].Name)); else region.append($('<option></option>').val(response[i].Id).text(response[i].Name)); } 
0
source
 var s_string = '<option>Select Value </option>'; for () // your for loop { s_string+=''; //your option tag code (appned fetch data in same variable and appned that variable after for loop end) } // appand s_string variable to your destination id or class (append) 
0
source

All Articles