<je**********@g mail.comwrote in message
news:de******** *************** ***********@m3g 2000hsc.googleg roups.com...
I'm designing a form where the user can decide how many options for a
poll he wants to add. There's a "+" button to dynamically add
textboxes with javascript, without a postback.
How do I access these newly generated <input type="text" id="..." />
elements with ASP.NET to save it to a database?
In a nutshell, you can't - at least, not in the normal way, because the
postback process only knows about controls which were created before the
page was rendered to the browser...
Fortunately, there's a fairly simple workaround. The following assumes
you're initiating the postback by means of an <asp:Button /webcontrol...
1) Add a hidden textbox to your page e.g.
<asp:HiddenFiel d ID="MyHiddenFie ld" runat="server" />
http://msdn.microsoft.com/en-us/libr...ddenfield.aspx
2) Add a client-side function to the <asp:Button /e.g.
<asp:Button ID="MyButton" runat="server" Value="Submit"
OnClick="MyButt on_Click" OnClientClick=" getTextBoxes(); " />
3) Create the client-side JavaScript function getTextBoxes() e.g.
<script type="text/javascript">
function getTextBoxes()
{
}
</script>
4) Add code to the above function to walk through the dynamic textboxes,
adding their id and value to the value of MyHiddenField so that it ends up
looking like e.g.
"txt001=Fir st value;txt002=Se cond value;txt003=Th ird value;"
etc
5) When the page is posted back, split the value of MyHiddenField on the
semi-colon character. This will give you a string array something like:
txt001=First value
txt002=Second value
txt003=Third value
Iterate through each element of the string array and split it on the equals
character - that will give you the ID of each dynamic textbox and its value.
--
Mark Rae
ASP.NET MVP
http://www.markrae.net