English 中文(简体)
如何使用JQuery在下拉列表中选择默认值
原标题:How to select default value in drop down list using JQuery

我想在下拉列表中选择“阿尔及利亚”作为默认选择值。我正在使用JSON数据格式的处理程序(LoadCountryList.ashx)从数据库中获取国家列表,并使用下面给出的Jquery s$.getJSON过程将其绑定到aspx页面上的下拉列表

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

最后我试着设置它的默认值“阿尔及利亚”。

$(objSelect).find("option[text= Algeria ]").attr("selected","selected"); 
OR
$(objSelect).find("option[value= 3 ]").attr("selected","selected");

但没用。有人建议我怎么做吗。

更新:

此外,我想显示等待消息,如正在加载。。。直到它从数据库中得到完整的国家列表。

最佳回答

要按值执行,只需使用val()(docs)方法。

$(objSelect).val( 3 );

根据文本内容,最安全的是使用filter()(docs)方法。

$(objSelect).find( option ).filter(function() {
    return this.text ===  Algeria ;
}).attr( selected , selected );

编辑:确保在回调getJSON()调用的内部执行

问题回答
$(objSelect).val("Algeria");

应该这样做。

这应该起作用:

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

试试这个:-

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

你也可以试试这个

$(objSelect).val(1);





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!