asp:TextBox不与javascript合作

时间:2018-05-05 01:23:47

标签: javascript html css asp.net

我试图在两个按钮的事件上填充TextBox。

<div class="numbers-row">
 <div onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty ) &amp;&amp; qty > 0 ) result.value--;return false;" class="dec qtybutton"><i class="fa fa-minus">&nbsp;</i></div>

 <asp:TextBox ID="qty" runat="server" class="qty" title="qty" maxlength="12" name="qty"></asp:TextBox>

 <div onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty )) result.value++;return false;" class="inc qtybutton"><i class="fa fa-plus">&nbsp;</i></div>
</div>

Image contains two buttons. On Onclick event minus button decremented the value and plus button increment the value, but the value is not reflecting on TextBox. But if i use html textbox like <code><input type="text" class="qty" title="Qty" value="1" maxlength="12" id="qty" name="qty"/></code> it works fine

图片包含两个按钮。在Onclick事件减号按钮递减值和加号按钮递增值,但该值不反映在TextBox上。但是,如果我使用像<input type="text" class="qty" title="Qty" value="1" maxlength="12" id="qty" name="qty"/>这样的html文本框,它可以正常工作

2 个答案:

答案 0 :(得分:1)

如果我没记错的话,ASP.NET会添加额外的标识符以确保ID是唯一的。当它在客户端呈现时,ID看起来更像ctl00$ContentPlaceHolder1$CustomUserControl1$qty。您可以在ASP.NET Web Server Control Identification 文档中了解有关此命名约定的更多信息。

要解决您的问题,您可以:

  • 如果您知道idqty结尾,请使用CSS属性选择器,例如document.querySelector('[id$="$qty"]')
  • 使用呈现的确切ID(更加绚丽)
  • 更改ASP.NET命名约定

答案 1 :(得分:1)

Asp.Net选中服务器控件的ID,以确保网页上元素的唯一ID。如果要使用相同的ID,请在asp:TextBox中使用ClientIDMode =“Static”。或者您可以使用

在javascript中获取输入引用
document.getElementById('<%=qty.ClientID%>')
相关问题