Reputation: 117
How can I access the value of a control (in CodeBehind) that was created by JavaScript dynamically?
I created the controls dynamically by using the following code:
var counter = 0;
var words;
var foo;//span tag
function add(i) {
var counter = 0;
var words;
var foo;//span tag asp in page where the controls to be added
if (i == 'ad') {
counter++;
//Create an input type dynamically.
foo = document.getElementById("dynamic")
tbnam = document.createElement("input") //textbox
tbdes = document.createElement("input") //textbox
lbnam = document.createElement("Label")
lbdes = document.createElement("Label")
before = document.createElement('br')
after = document.createElement('br')
//Assign different attributes to the element.
wordsnam = document.createTextNode("Item")
wordsdes = document.createTextNode("Descrip")
tbnam.setAttribute("type", "TextBox");
tbdes.setAttribute("type", "TextBox");
tbnam.setAttribute("Id", "tbdynamicnam" + counter);
tbdes.setAttribute("Id", "tbdynamicdes" + counter);
lbnam.setAttribute("Id", "lbdynamicnam" + counter);
lbdes.setAttribute("Id", "lbdynamicdes" + counter);
before.setAttribute("Id", "bf" + counter);
after.setAttribute("Id", "af" + counter);
lbnam.appendChild(wordsnam)
lbdes.appendChild(wordsdes)
//Append the element in page (in span).
foo.appendChild(before);
foo.appendChild(lbnam);
foo.appendChild(tbnam);
foo.appendChild(lbdes);
foo.appendChild(tbdes);
foo.appendChild(after);
}
}
Upvotes: 2
Views: 981
Reputation: 21137
When the form is submitted it will be in the Request.Form collection, you can access it easiest in the Request object which will check all collections(QueryString, Form, Cookies, and ServerVariables)
JavaScript:
tbnam = document.createElement("input") //textbox
tbnam.setAttribute("type", "TextBox");
tbnam.setAttribute("Id", "tbdynamicnam" + counter);
tbnam.setAttribute("name", "tbdynamicnam" + counter);
Code-behind:
string newval = Request["newelementname"];
As mentioned below by James Montagne, you will need a form element name.
Upvotes: 6