虽然我试图通过.val()获取文本框的值,但它始终显示“未定义”。 以下是我正在使用的代码。请帮帮我朋友。
<asp:TextBox runat="server" ID="txtComment" Width="650" />
<asp:Button runat="server" ID="btnSubmitComment" Text="Submit" />
$(document).ready(function () {
$('input[id$=btnSubmitComment]').click(function () {
var comment = $("#txtComment").val();
alert(comment);
});
答案 0 :(得分:5)
asp.net填充元素返回的id
。看起来您在click语句中使用它。你试过这个吗?
$(document).ready(function () {
$('input[id$=btnSubmitComment]').click(function () {//you are using the [id$=] selector here.
var comment = $("input[id$=txtComment]").val();//use it here too
alert(comment);
});
或者您可以使用<%= txtComment.ClientID %>
,但我个人从未使用过它。我相信你需要告诉asp.net将JavaScript文件嵌入到页面中,以便客户端id
被放置在适当的位置。我将寻找这个潜在解决方案的链接。
答案 1 :(得分:3)
这是正常的,当.net呈现HTML时,texbox的ID就像ct_001_txtComment。
或者您可以在web.config中更改以下选项,以使页面元素中的ID为静态
controlRenderingCompatibilityVersion="4.0" clientIDMode="Static"
或者您可以通过以下客户端ID获取它:&lt;%= txtComment.ClientID%&gt;
答案 2 :(得分:1)
asp.net上的一种标准方法是获取呈现的id并在javascript上使用它:
$(document).ready(function () {
$('#<%=btnSubmitComment.ClientID%>').click(function () {
var comment = $('#<%=txtComment.ClientID%>').val();
alert(comment);
});
(从你使用ID的那一刻开始,而不是用其他方式来选择控件,比如css,类型等。