[英]ASP.NET DropDownList JavaScript/jQuery getting selected value and populating items
I've been stuck on this for 2 days now. 我已经坚持了两天了。 I originally used HTMLSelect elements and had success until I realized I had no idea how to assign value to them from the code behind.
我最初使用HTMLSelect元素并获得成功,直到我意识到我不知道如何通过后面的代码为它们分配值。 Here was the code when using HTMLSelect elements that made the page elements behave the way I wanted:
这是使用HTMLSelect元素时的代码,这些代码使页面元素的行为符合我想要的方式:
<select id="cboCountry" class="autoTBComplete"/>
<select id="cboState" class="autoTBComplete" />
<script type="text/javascript">
$(document).ready(function () {
$("#cboCountry").bind("change", ValidateCountryInput);
$("#cboState").bind("change", ValidateStateInput);
$.ajax({
type: "POST",
url: "AjaxService.asmx/GetCountryList",
contentType: "application/json; charset=utf-8",
data: "{}",
datatype:"json",
success: function (data) {
var d = data.d
$(d).each(function (i) {
$('#cboCountry').append("<option value=" + d[i] + ">" + d[i] + "</option>");
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
function ValidateCountryInput() {
if (CheckUSAorCAN()) {
$.ajax({
type: "POST",
url: "AjaxService.asmx/GetStateList",
contentType: "application/json; charset=utf-8",
data: "{}",
datatype: "json",
success: function (data) {
var d = data.d
$(d).each(function (i) {
$('#cboState').append("<option value=" + d[i] + ">" + d[i] + "</option>");
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
$("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
}
else {
$("[id$='cboState']").val("");
$("[id$='cboState']").attr('style', "width:5%");
$("[id$='cboState']").classname ="autotbComplete";
};
};
function ValidateStateInput() {
var txt = $('#cboState').val();
if (CheckUSAorCAN()) {
if (txt.length > 0) {
$("[id$='cboState']").attr('style', "width:64%");
$("[id$='cboState']").classname = "autotbComplete";
}
else {
$("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
}
}
else {
$("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
};
}
function CheckUSAorCAN() {
var txt = $('#cboCountry').val();
txt = toAllCaps(txt);
txt = txt.replace("([^A-Z])+");
return "US" == txt || "USA" == txt || "UNITEDSTATES" == txt || "CANADA" == txt;
}
function toAllCaps(string) { //jQuery toUpperCase() doesn't work on strings for IE 6-10
if (string != null) {
var input = string.split("")
for (i = 0; i < input.length; i++) {
input[i] = string.charAt(i).toUpperCase()
};
return input.join("")
}
return string
};
After having that working, I realized I had a problem in the code behind, specifically in the following function where I am assigning values to or retrieving a value from the element. 完成该工作后,我意识到我在后面的代码中存在问题,特别是在以下函数中,我在其中为元素分配值或从中获取值。 I can use the Response.Params to get the value from the box, but don't know how to assign the value or how to hide/disable the field from the code behind, since I can't do cboCountry.enabled = false on a select element from code behind.
我可以使用Response.Params从框中获取值,但是不知道如何分配值或如何从后面的代码中隐藏/禁用该字段,因为我无法在以下位置执行cboCountry.enabled = false从后面的代码中选择一个元素。 The code works if the element is an ASP.NET DropDownList (Note: I removed irrelevant fields from this property. The cbo prefix is leftovers from when the app was just a WinApp using comboboxes).
如果该元素是ASP.NET DropDownList,则该代码有效(注意:我从该属性中删除了不相关的字段。cbo前缀是应用程序只是使用组合框的WinApp时的剩余值)。
Private Property InputFieldsControl As CustomerDataFields
Get
Dim cdf As New CustomerDataFields
cdf.Country = cboCountry.Text
cdf.State = cboState.Text
Return cdf
End Get
Set(ByVal cdf As CustomerDataFields)
If Not cboCountry.Items.Contains(New ListItem(cdf.Country)) Then
cboCountry.Items.Add(cdf.Country)
End If
cboCountry.Text = cdf.Country
If Not cboState.Items.Contains(New ListItem(cdf.State)) Then
cboState.Items.Add(cdf.State)
End If
cboState.Text = cdf.State
End Set
End Property
Since realizing that the HTMLSelect element will not work with my code behind. 由于意识到HTMLSelect元素将无法与我后面的代码一起使用。 I tried to make the same webpage and javascript work with DropDownLists, but am not having success.
我试图使相同的网页和javascript与DropDownLists一起使用,但没有成功。 The code that is changed from above is below.
从上面更改的代码如下。 Pay attention to the comments as those are the new problems.
注意这些评论,因为它们是新问题。 Specifically the events not firing and the CheckUSAorCAN() constantly retrieving a null value for the selected value from cboCountry.
具体来说,事件未触发,并且CheckUSAorCAN()不断从cboCountry中检索所选值的空值。
<asp:DropDownList Width="66%" CssClass="tbSkin" ID="cboCountry" runat="server" ></asp:DropDownList>
<asp:DropDownList Width="66%" CssClass="tbSkin" ID="cboState" runat="server" ></asp:DropDownList>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "AjaxService.asmx/GetCountryList",
contentType: "application/json; charset=utf-8",
data: "{}",
datatype:"json",
success: function (data) {
var d = data.d;
$(d).each(function (i) {
var ddlref = document.getElementById("cphContents_InputParams_cboCountry");
addItem(ddlref,d[i]);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
$("#cboCountry").bind("change", onCountryChange); //does not bind or fire the event
$("#cboState").bind("change", onStateChange); //does not bind or fire the event
});
function onCountryChange(e) {
if (CheckUSAorCAN()) {
$.ajax({
type: "POST",
url: "AjaxService.asmx/GetStateList",
contentType: "application/json; charset=utf-8",
data: "{}",
datatype: "json",
success: function (data) {
var d = data.d;
$(d).each(function (i) {
var ddlref = document.getElementById("cphContents_InputParams_cboState");
addItem(ddlref, d[i]);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
$("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
}
else {
$("[id$='cboState']").val("");
$("[id$='cboState']").attr('style', "width:5%");
$("[id$='cboState']").classname = "autotbComplete";
};
};
function onStateChange(e) {
var txt = $('#cboState').val();
if (CheckUSAorCAN()) {
if (txt.length > 0) {
$("[id$='cboState']").attr('style', "width:64%");
$("[id$='cboState']").classname = "autotbComplete";
}
else {
$("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
};
}
else {
$("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
};
};
function CheckUSAorCAN() {
var txt = $('#cboCountry').val();
var e = document.getElementById("cphContents_InputParams_cboState");
var index = e.selectedIndex; //does not work
var strUser = e.options[e.selectedIndex]; //does not work
if (txt != null) { //always comes up null
txt = toAllCaps(txt);
txt = txt.replace("([^A-Z])+");
return "US" == txt || "USA" == txt || "UNITEDSTATES" == txt || "CANADA" == txt;
}
return false;
};
function addItem(ddlref, item) {
var option1 = document.createElement("option");
option1.text = item;
option1.value = item;
ddlref.options.add(option1);
};
Because the change events are not firing after binding via jQuery, I bound them in the markup code like so: 因为通过jQuery绑定后change事件没有触发,所以将它们绑定在标记代码中,如下所示:
<asp:DropDownList Width="66%" CssClass="autoTBComplete" ID="cboCountry" runat="server" onchange="onCountryChange()"></asp:DropDownList>
However, now the onCountryChange() does fire, but the value in the cboCountry comes back as nothing for the CheckUSAorCAN() function. 但是,现在onCountryChange()确实可以触发,但是cboCountry中的值作为CheckUSAorCAN()函数的内容返回为零。
I'm out of ideas. 我没主意了。 How do I make this work?
我该如何工作?
EDIT: If I set runat="server" on the HTMLSelect markup so that I can access it from the code behind, it does the same thing as the DropDownList where the event's will not fire unless I set the onchange event inside the markup. 编辑:如果我在HTMLSelect标记上设置了runat =“ server”,以便可以从后面的代码访问它,则它与DropDownList的作用相同,除非我在标记内设置onchange事件,否则该事件将不会触发。 Then the selected value is null everytime, just like it was for the DropDownList
然后所选值每次都为null,就像DropDownList一样
Finally got it working. 终于成功了。 I used classname instead of ID for jQuery.
我为jQuery使用类名而不是ID。 Here is the working code for future reference and others coming from google.
这是工作代码,供将来参考,以及其他来自Google的代码。
Markup: 标记:
<select name="cboCountry" id="cboCountry" class="autoTBComplete cboCountry" runat="server" />
<select id="cboState" name="cboState" class="autoTBComplete cboState" runat="server" />
Script: 脚本:
<script type="text/javascript">
$(document).ready(function () {
$(".cboCountry").bind("change", ValidateCountryInput);
$(".cboState").bind("change", ValidateStateInput);
$.ajax({
type: "POST",
url: "AjaxService.asmx/GetCountryList",
contentType: "application/json; charset=utf-8",
data: "{}",
datatype: "json",
success: function (data) {
var d = data.d
$(d).each(function (i) {
$(".cboCountry").append("<option value=" + d[i] + ">" + d[i] + "</option>");
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
function ValidateCountryInput() {
if (CheckUSAorCAN()) {
$.ajax({
type: "POST",
url: "AjaxService.asmx/GetStateList",
contentType: "application/json; charset=utf-8",
data: "{}",
datatype: "json",
success: function (data) {
var d = data.d
$(d).each(function (i) {
$(".cboState").append("<option value=" + d[i] + ">" + d[i] + "</option>");
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
$(".cboState").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
}
else {
$(".cboState").val("");
$(".cboState").attr('style', "width:5%");
$(".cboState").classname = "autotbComplete";
};
};
function ValidateStateInput() {
var txt = $('.cboState').val();
if (CheckUSAorCAN()) {
if (txt.length > 0) {
$(".cboState").attr('style', "width:64%");
$(".cboState").classname = "autotbComplete";
}
else {
$(".cboState").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
}
}
else {
$(".cboState").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
};
}
Code Behind: 背后的代码:
Protected WithEvents cboCountry As Global.System.Web.UI.HtmlControls.HtmlSelect
Protected WithEvents cboState As Global.System.Web.UI.HtmlControls.HtmlSelect
Private Property InputFieldsControl As CustomerDataFields
Get
Dim cdf As New CustomerDataFields
cdf.Country = Request.Params("ctl00$cphContents$InputParams$cboCountry")
cdf.State = Request.Params("ctl00$cphContents$InputParams$cboState")
Return cdf
End Get
Set(ByVal cdf As CustomerDataFields)
If Not cboCountry.Items.Contains(New ListItem(cdf.Country)) Then
cboCountry.Items.Add(cdf.Country)
End If
cboCountry.SelectedIndex = GetHTMLSelectIndex(cboCountry, cdf.Country)
If Not cboState.Items.Contains(New ListItem(cdf.State)) Then
cboState.Items.Add(cdf.State)
End If
cboState.SelectedIndex = GetHTMLSelectIndex(cboState, cdf.State)
End Set
End Property
Private Function GetHTMLSelectIndex(elem As HtmlSelect, value As String) As Integer
Return elem.Items().IndexOf(elem.Items.FindByText(value))
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.