Reputation: 94
My aspx page contains list of products along with dynamically generated textboxes and one order button with each product.
Textboxes and buttons are generated at runtime with ids like txt110234,txt110235...so on for textboxes and btn110234,btn110235...so on for buttons.
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-
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:
How can i get the value of textbox?Any suggestion will be appreciated..
Upvotes: 0
Views: 4778
Reputation: 13286
The error you got is because you can't involve javascript inside the "<%= .. %>" block. 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.
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 + "')";
Upvotes: 2
Reputation: 3268
Suggestion: One way of doing this is to use jQuery css selector. You can assign a particular cssclass to all your input textbox and retrieve all of them via jQuery selector.
For example, on generating textboxes dynamically, you can assign them CssClass =".productQuantity"
and then later use jQuery selector something like $('.productQuantity')
I personally prefer this approach If I would like to traverse to multiple elements. This saves me from dealing with Ids etc.
Upvotes: 0