Asp.net javascript add new textbox and post

A classic ASP.NET question!

To add a new TextBox dynamically using JavaScript and post the form data to the server, you can follow these steps:

Step 1: Add a JavaScript function to add a new TextBox

In your ASPX page, add a JavaScript function that will add a new TextBox to the form:

<script type="text/javascript">
    function addTextBox() {
        var textBox = document.createElement("input");
        textBox.type = "text";
        textBox.name = "TextBox" + (document.forms[0].elements.length + 1);
        document.forms[0].appendChild(textBox);
    }
</script>

This function creates a new input element with type text, sets its name attribute to a unique value (e.g., TextBox1, TextBox2, etc.), and appends it to the form using document.forms[0].appendChild().

Step 2: Add a button to trigger the JavaScript function

Add a button to your ASPX page that will trigger the JavaScript function when clicked:

<asp:Button ID="btnAddTextBox" runat="server" Text="Add TextBox" OnClientClick="addTextBox();" />

Step 3: Update the form's action attribute

To post the form data to the server, you need to update the form's action attribute to point to your ASPX page:

<form id="form1" runat="server" action="Default.aspx">
    <!-- other form elements -->
    <asp:Button ID="btnAddTextBox" runat="server" Text="Add TextBox" OnClientClick="addTextBox();" />
</form>

Step 4: Handle the form post on the server-side

In your ASPX page's code-behind, you can access the posted form data using the Request.Form collection:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Form.Count > 0)
    {
        foreach (string key in Request.Form.AllKeys)
        {
            if (key.StartsWith("TextBox"))
            {
                // Process the posted TextBox value
                string value = Request.Form[key];
                //...
            }
        }
    }
}

In this example, we loop through the Request.Form collection and check if the key starts with "TextBox". If it does, we process the posted value.

That's it! When you click the "Add TextBox" button, the JavaScript function will add a new TextBox to the form, and when you submit the form, the posted data will be available on the server-side.

Note that this is a basic example, and you may want to add additional validation and error handling to your code.