Sukhjeevan
Sukhjeevan

Reputation: 3156

How to select default value in drop down list using JQuery

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.

enter image description here

UPDATE:

Also i want to show waiting message like Loading... until it get complete country list from database.

Upvotes: 2

Views: 20253

Answers (5)

Mohammed Irfan
Mohammed Irfan

Reputation: 1

yoy can also try this one

$(objSelect).val('1');

Upvotes: 0

smita
smita

Reputation: 9

Try this:-

$(objSelect).combobox("destroy");     
$(objSelect).val("Algeria");
$(objSelect).combobox();

Upvotes: 0

user113716
user113716

Reputation: 322502

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.

Upvotes: 3

GunnerL3510
GunnerL3510

Reputation: 715

This should work:

$(objSelect).val("3");

Upvotes: 0

Rob Williams
Rob Williams

Reputation: 1470

$(objSelect).val("Algeria");

should do it.

Upvotes: 1

Related Questions