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.

Share:
19,300
Sukhjeevan
Author by

Sukhjeevan

asp.net , c# , vb.net , ajax , jQuery , mssql server

Updated on June 13, 2022

Comments

  • Sukhjeevan
    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.

    enter image description here

    UPDATE:

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

  • Sukhjeevan
    Sukhjeevan about 13 years
    Thanks 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
    Sukhjeevan about 13 years
    one 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
    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 the getJSON callback, do $('#myContainer').text('')