How to select default value in drop down list using JQuery
19,300
Solution 1
To do it by value, you can just use the val()
(docs) method.
$(objSelect).val('3');
By text content, safest is to use the filter()
(docs) method.
$(objSelect).find('option').filter(function() {
return this.text === 'Algeria';
}).attr('selected','selected');
EDIT: Make sure you're doing it inside the callback to the getJSON()
call.
Solution 2
$(objSelect).val("Algeria");
should do it.
Comments
-
Sukhjeevan almost 2 years
I want to select "Algeria" as default selected value in drop down list.I am fetching countrylist from database using handler ( LoadCountryList.ashx ) in JSON data format and binding it to dropdownlist on aspx page using Jquery's $.getJSON precedure given below
function AddOptions(objSelect) { var URL ="~/LoadCountryList.ashx"; $.getJSON(URL,function(countries){ $.each(countries,function(){ var vCountry = this['Country']; $(objSelect).append($("<option></option>").val(this['ID']).html(vCountry)); }); }); }
and finally i tried to set its default value "Algeria".
$(objSelect).find("option[text='Algeria']").attr("selected","selected"); OR $(objSelect).find("option[value='3']").attr("selected","selected");
but its not worked.Does anyone suggest me how to do it.
UPDATE:
Also i want to show waiting message like Loading... until it get complete country list from database.
-
Sukhjeevan about 13 yearsThanks patric it worked like charm.actually i was doing this work outside getJSON() function that's why it wasn't working.thanks a lot.
-
Sukhjeevan about 13 yearsone more thing i want to show waiting message like Loading... until it get complete country list from database.can u tell me how can i do that.
-
user113716 about 13 years@Sukhi: Sure. Just decide where the message should go, then right before the
getJSON
request, do$('#myContainer').text('loading...')
and inside thegetJSON
callback, do$('#myContainer').text('')