简体   繁体   English

如何在asp.net中获取动态创建的文本框Web控件的价值

[英]How to get value of dynamically created textbox web control in asp.net

My aspx page contains list of products along with dynamically generated textboxes and one order button with each product. 我的aspx页面包含产品列表以及动态生成的文本框和每个产品的一个订单按钮。

Textboxes and buttons are generated at runtime with ids like txt110234,txt110235...so on for textboxes and btn110234,btn110235...so on for buttons. 文本框和按钮在运行时生成,其中包含txt110234,txt110235 ......等文本框和btn110234,btn110235 ...等等按钮。

Each time user have to enter quantity in the textbox and press order button associated with any product to place any order. 每次用户必须在文本框中输入数量并按下与任何产品相关联的订单按钮以下订单。

Every thing is working fine but now i want to do it using ajax,so i need to get the value entered by user in text box.I want to do something like this- 每件事都很好但现在我想用ajax做,所以我需要在文本框中输入用户输入的值。我想做这样的事情 -

   var quan = document.getElementById('<%= txt' + id + '.ClientID%>').value;

But its giving me the following error. 但它给了我以下错误。

Compiler Error Message: CS1012: Too many characters in character literal Source Error: 编译器错误消息:CS1012:字符文字中的字符太多源错误:

How can i get the value of textbox?Any suggestion will be appreciated.. 我怎样才能获得文本框的价值?任何建议都将受到赞赏..

The error you got is because you can't involve javascript inside the "<%= .. %>" block. 你得到的错误是因为你不能在“<%= ..%>”块中包含javascript。 Also this doesn't look possible since the "<%= .. %>" expression is evaluated in server before the page is rendered, but your "id" is a client side variable. 此外,这似乎不可能,因为在呈现页面之前在服务器中评估“<%= ..%>”表达式,但您的“id”是客户端变量。

You can set the script in server side like that: 您可以在服务器端设置脚本,如下所示:

client side code: 客户端代码:

function foo(ctlID)
{
   var quan = document.getElementById(ctlID).value;
}

server side code: 服务器端代码:

TextBox txt = new TextBox();
txt.ID = "SomeID";
Form.Controls.Add(txt);
Button btn = new Button();
btn.ID = "someID";
btn.OnClientClick = "foo('" + txt.ClientID + "')";

Suggestion: One way of doing this is to use jQuery css selector. 建议:这样做的一种方法是使用jQuery css选择器。 You can assign a particular cssclass to all your input textbox and retrieve all of them via jQuery selector. 您可以为所有输入文本框分配特定的cssclass,并通过jQuery选择器检索所有这些cssclass。

For example, on generating textboxes dynamically, you can assign them CssClass =".productQuantity" 例如,在动态生成文本框时,可以为它们分配CssClass =“。productQuantity”

and then later use jQuery selector something like $('.productQuantity') 然后使用jQuery选择器,如$('。productQuantity')

I personally prefer this approach If I would like to traverse to multiple elements. 我个人更喜欢这种方法如果我想遍历多个元素。 This saves me from dealing with Ids etc. 这使我免于处理ID等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM