我有一个包含2个值的下拉列表 - Y(是)和N(否)。如果我选择值“Y”,将显示某个<td>
,但我无法实现该结果。我的代码出了什么问题?到目前为止,我只能隐藏它。
这是我的asp.net代码
<tr class="inputRows">
<td class="colHead">Mailing</td>
<td>
<asp:DropDownList ID="ddlMail" runat="server">
<asp:ListItem Selected="True" Value="empty">- - -</asp:ListItem>
<asp:ListItem Value="Y">Yes</asp:ListItem>
<asp:ListItem Value="N">No</asp:ListItem>
</asp:DropDownList>
</td>
<td class="colHead" id="lblC">Carrier</td>
<td id="ddlC">
<asp:DropDownList ID="ddlCarrier" runat="server">
<asp:ListItem Selected="True" Value="empty">- - -</asp:ListItem>
<asp:ListItem Value="Dlv">Delivery</asp:ListItem>
<asp:ListItem Value="Pck">Pick-up</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
这是我的jQuery代码
$(document).ready(function () {
$('#lblC').hide();
$('#ddlC').hide();
var i = document.getElementById("ddlMail");
var value = i.options[i.selectedIndex].text;
if (value == "Y") {
$('#lblC').show();
$('#ddlC').show();
}
});
答案 0 :(得分:1)
更改所选项目时使用更改
$(document).ready(function () {
change($("#ddlMail"));
$("#ddlMail").change(function () {
change($(this));
});
});
function change(obj){
if ($(obj).val() == "Y") {
$('#lblC').show();
$('#ddlC').show();
}
else{
$('#lblC').hide();
$('#ddlC').hide();
}
}
答案 1 :(得分:0)
您可以使用id
ClientID
var i = document.getElementById("<%=ddlMail.ClientID%>")
此外,您需要获取所选选项的值,而不是文本,因此您可以使用:
var value = i.options[i.selectedIndex].value;
而不是:
var value = i.options[i.selectedIndex].text;
最终代码如下:
$(document).ready(function () {
$('#lblC').hide();
$('#ddlC').hide();
var i = document.getElementById("<%=ddlMail.ClientID%>");
var value = i.options[i.selectedIndex].value;
if (value == "Y") {
$('#lblC').show();
$('#ddlC').show();
}
});
答案 2 :(得分:0)
$(document).ready(function () {
$('#lblC').hide();
$('#ddlC').hide();
var i = document.getElementById("<%=ddlMail.ClientID%>")
var value = i.options[i.selectedIndex].value;
if (value == "Y") {
$('#lblC').show();
$('#ddlC').show();
}
});
在dropdownlist控件中使用ClientID,因为它是服务器控件。
答案 3 :(得分:0)
使用<%=ddlMail.ClientID%>
或更好
$("select[id$=ddlMail]").val();
答案 4 :(得分:0)
您的下拉列表会在时间或渲染时更改ID,因此您应该使用clientId
或classname
来引用下拉列表。如果您为该下拉列表指定了一个类名,那么您的代码应该类似于
$(".ddlCarrier").change(function () {
if ($(this).val() == "Y") {
$('#lblC').show();
$('#ddlC').show();
}
});
HTML
<asp:DropDownList ID="ddlCarrier" class="ddlCarrier" runat="server">