我正在使用jquery向下拉列表添加选项,如下所示。
function GetAssociates(StoreNum,dropdownid) {
$.ajax({
type: "POST",
url: "Appointment.aspx/BindAssociates",
data: "{storeNumber:" + StoreNum + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result){
var rs = result.d;
var select = $("#" + dropdownid);
//var select = document.getElementById(dropdownid);
for (var i = 0; i < rs.length; i++) {
var opt = rs[i].trim();
select.append(new Option(opt,opt));
}
},
error: function(result){
alert("Failed to load dropdown" + result);
}
});
}
这完美无缺,我可以看到dropwdown中的值。现在我尝试使用jquery选择特定值,如下所示,但它没有选择值。
$("#MST_CPH_AddAppointment_ddlAptAssociateName").val("MyValue");
如果我在设计时添加值,如上面选择MyValue的代码工作正常。
<asp:DropDownList ID="ddlAptAssociateName" runat="server" CssClass="DropdownList">
<asp:ListItem>SomeValue</asp:ListItem>
<asp:ListItem>MyValue</asp:ListItem>
</asp:DropDownList>
请帮我这样做。
答案 0 :(得分:1)
你去了 我无法抗拒添加jsDoc:D
/**
*
* @param StoreNum
* @param dropdownid
* @param {Function} callback
* @constructor
*/
function GetAssociates( StoreNum, dropdownid, callback ) {
$.ajax( {
type : "POST",
url : "Appointment.aspx/BindAssociates",
data : "{storeNumber:" + StoreNum + "}",
contentType: "application/json; charset=utf-8",
dataType : "json",
success : function ( result ) {
var rs = result.d;
var select = $( "#" + dropdownid );
//var select = document.getElementById(dropdownid);
for ( var i = 0; i < rs.length; i++ ) {
var opt = rs[ i ].trim();
select.append( new Option( opt, opt ) );
}
// apply will run the function with 'this' as first committed argument-> select
callback.apply( select );
},
error : function ( result ) {
alert( "Failed to load dropdown" + result );
}
} );
}
function load() {
// GetAssociates is a constructor due to uppercased name
// my idea will mark this as error -> never mind in your case
GetAssociates( 1, "MST_CPH_AddAppointment_ddlAptAssociateName", function () {
this.val( "MyValue" );
} );
}
答案 1 :(得分:0)
您使用.val()
错误。您可以通过执行以下操作获得价值:
var myVal = $("#MST_CPH_AddAppointment_ddlAptAssociateName").val();
您可以通过执行以下操作将值设置为MyValue
:
$("#MST_CPH_AddAppointment_ddlAptAssociateName").val("MyValue");