How do I modify this jQuery to allow for more controls?

Simflex 301 Reputation points
2023-01-03T19:53:00.06+00:00

Greetings again mates.

I have been trying quite unsuccessfully for the last three days to try to figure out how to dynamically add rows based on selecting DropDownList values.

There are quite a good number of examples on how to do this by clicking a button to add more rows but my solution is different.

The sample that I was able to find, uses jquery to allow users to add a row dynamically based on DropDownList selected value.

We would like to modify this jquery to allow us to add more textbox and dropdownlist controls to any dynamically created row because we do have several textbox controls.

Even better, if possible, can this be done with asp.net?

Here is what I have so far.

Your generous assistance is greatly appreciated in advance.

//HTML  
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="waterCollections.aspx.vb" Inherits="toilets" %>  

<!DOCTYPE html>  

<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
<script type="text/javascript">  
    $(function () {  
        var values = eval('<%=Values%>');  
        if (values != null) {  
            var html = "";  
            $(values).each(function () {  
                var div = $("<div />");  
                div.html('<input name ="DynamicTextBox" type="text" value ="' + this + '" />');  
                $("#divDynamic").append(div);  
            });  
        }  
        $('[id*=ddlNumber]').change(function () {  
            $("#divDynamic").empty();  
            for (var i = 0; i < $(this).val(); i++) {  
                var textbox = $(document.createElement('div')).attr("id", 'divTxt' + i);  
                textbox.after().html('<input name ="DynamicTextBox" type="text" />');  
                textbox.appendTo("#divDynamic");  
            }  
        });  
    });  
</script>  
</head>  
<body>  
    <form id="form1" runat="server">  
<div>  
<div>  
    <asp:DropDownList ID="ddlNumber" runat="server">  
        <asp:ListItem Text="1" Value="1"></asp:ListItem>  
        <asp:ListItem Text="2" Value="2"></asp:ListItem>  
        <asp:ListItem Text="3" Value="3"></asp:ListItem>  
    </asp:DropDownList>  
    <br />  
    <div id="divDynamic">  <%--<! -- Replace with Textbox and DropDownList controls--%>  
    </div>  

// I would like to be able to select a value from the dropdown above and a row containing textboxes and dropdowns like the example below, will be created.
asp:TableCell
<asp:DropDownList ID="ddlWater" AppendDataBoundItems="true" runat="server">
<asp:ListItem Value="1.30" >1.30 GPF</asp:ListItem>
<asp:ListItem Value="1.28">1.28 GPF</asp:ListItem>
<asp:ListItem Value="0.80">0.80 GPF</asp:ListItem>
</asp:DropDownList>
</asp:TableCell>
asp:TableCell
$<asp:TextBox ID="txt_amount" runat="server" /></asp:TableCell>
asp:TableCell
<asp:TextBox ID="modelNumber" runat="server" /></asp:TableCell>
asp:TableCell
<asp:TextBox ID="dateReUpgraded" runat="server" /></asp:TableCell>

    <br />  
    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />  
</div>  
</div>  
 </form>  
</body>  
</html>  

//VB.NET  
Imports System.Data  
Imports System.Data.SqlClient  
Imports System.Configuration  
Partial Class waterCollections  
    Inherits System.Web.UI.Page  
    Private con As String = ConfigurationManager.ConnectionStrings("conStr").ConnectionString  
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  
        If Not IsPostBack Then  
        End If  
    End Sub  
    Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)  
        Dim textboxValues As String() = Request.Form.GetValues("DynamicTextBox")  
        Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()  
        Me.Values = serializer.Serialize(textboxValues)  
        For Each textboxValueAs String In textboxValues  
        Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conSting").ConnectionString)  
                Using cmd As SqlCommand = New SqlCommand("INSERT INTO Customers (@CustomerId) VALUES(@CustomerId)", con)  
                    con.Open()  
                    cmd.Parameters.AddWithValue("@CustomerId", textboxValue)  
                    cmd.ExecuteNonQuery()  
                    con.Close()  
                End Using  
            End Using  
        Next  
    End Sub  

End Class  
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,373 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,569 questions
{count} votes

Accepted answer
  1. AgaveJoe 26,201 Reputation points
    2023-01-04T11:53:44.447+00:00

    Unfortunately, what the user's want is as I stated it.

    You missed the point. Web Forms is the technology selected for this project. Therefore, you should use the tools that come with Web Forms to build a solution.

    Below is a basic example of using a standard Repeater control to dynamically generate inputs.

    Markup

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebFormsDemo.RepeaterDemo._default" %>  
      
    <!DOCTYPE html>  
      
    <html xmlns="http://www.w3.org/1999/xhtml">  
    <head runat="server">  
        <title></title>  
    </head>  
    <body>  
        <form id="form1" runat="server">  
            <div>  
                <asp:DropDownList ID="ddlNumber" runat="server" OnSelectedIndexChanged="ddlNumber_SelectedIndexChanged" AutoPostBack="true">  
                    <asp:ListItem Text="--Select--" Value="0"></asp:ListItem>  
                    <asp:ListItem Text="1" Value="1"></asp:ListItem>  
                    <asp:ListItem Text="2" Value="2"></asp:ListItem>  
                    <asp:ListItem Text="3" Value="3"></asp:ListItem>  
                </asp:DropDownList>  
            </div>  
            <div>  
                <asp:Repeater ID="DynamicRepeater" runat="server">  
                    <HeaderTemplate>  
                        <table border="1">  
                            <tr>  
                                <td><b>Item 1</b></td>  
                                <td><b>Item 2</b></td>  
                            </tr>  
                    </HeaderTemplate>  
                    <ItemTemplate>  
                        <tr>  
                            <td>  
                                <asp:TextBox ID="Item1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Item1") %>'></asp:TextBox>  
                            </td>  
                            <td>  
                                <asp:TextBox ID="Item2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Item2") %>'></asp:TextBox>  
                            </td>  
                        </tr>  
                    </ItemTemplate>  
                    <FooterTemplate>  
                        </table>  
                    </FooterTemplate>  
                </asp:Repeater>  
            </div>  
        </form>  
    </body>  
    </html>  
    

    Code behind

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.UI;  
    using System.Web.UI.WebControls;  
      
    namespace WebFormsDemo.RepeaterDemo  
    {  
        public partial class _default : System.Web.UI.Page  
        {  
            protected void Page_Load(object sender, EventArgs e)  
            {  
      
            }  
      
            protected void ddlNumber_SelectedIndexChanged(object sender, EventArgs e)  
            {  
                List<ItemsModel> Items = new List<ItemsModel>();  
                int rows = 0;  
                int.TryParse(ddlNumber.SelectedValue, out rows);  
      
                for(int i = 0; i < rows; i++)  
                {  
                    Items.Add(new ItemsModel());  
                }  
      
                DynamicRepeater.DataSource = Items.Count == 0 ? null : Items;  
                DynamicRepeater.DataBind();  
            }  
      
        }  
      
        public class ItemsModel  
        {  
            public string Item1 { get; set; } = string.Empty;  
            public string Item2 { get; set; } = string.Empty;  
        }  
    }  
    

    The rest is up to you. I image you'll add a button to submit the user's inputs. Update a database table. Finally update any data bound controls that display records.

    Reference documentation
    https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.repeater?view=netframework-4.8.1

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Simflex 301 Reputation points
    2023-01-04T03:49:52.673+00:00

    @QiYou-MSFT , thanks for your response.

    Can you please assist?

    I already have the dropdown as shown in my original post.

    I also have the Save() method.

    My issue is how to use the dropdownlist to generate the rows. Each generated row needs to have the ability to have multiple controls like textboxes and dropdownlist.

    Thanks again for your help.

    0 comments No comments

  2. Simflex 301 Reputation points
    2023-01-04T15:55:08.753+00:00

    Oh wow, I was just too caught up with trying to do it one way.

    Thank you.

    Ok, I will follow the link to hopefully get an idea of how to grab the selected rows and insert into the DB.

    Many thanks for your help @AgaveJoe

    0 comments No comments