Pinu
Pinu

Reputation: 7520

ASP.NET - Jquery to add textbox and dropdown list dynamically

I need to be able provide a table on web page with one row which has a two drop down list and one textbox and the user's should be able to add any number of rows they want. I need to to this using jquery so that i can avoid post back. Is this possible to be done in Jquery and if it is possible i was looking for some example which will be like a pointer

Upvotes: 0

Views: 3577

Answers (1)

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

This should get you started... save as a .html file for an example

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        function createTextbox(){
            return "<input type='text' />"
        }
        function createDropDown(){
            return "<select><option>One</option><option>Two</option><option>Three</option></select>"
        }
        function createRow(){
            return "<tr><td>" + createTextbox() + "</td><td>" + createDropDown() + "</td><td>" + createDropDown() + "</td></tr>";
        }
        function getValuesForPostback(){
            //format as XML, JSON, or Whatever
            var ToReturn = "<items>"; 
            $('#sampleTable tr').each(function(){
                ToReturn += "<item>";
                //Get the textbox value
                ToReturn += "<text>" + $(this).find('input[type=text]').val() + "</text>";

                //Get the select values
                $(this).find('select option:selected').each(function(){
                    ToReturn += "<select>" + $(this).val() + "</select>";
                });
                ToReturn += "</item>";
            });
            ToReturn += "</items>";
            return ToReturn;
        }
        function submitValues()
        {
            alert(getValuesForPostback());
            //NOW: Just ajax or post back this value to the server and parse for your data.
        }
        $(document).ready(function(){
            $('#sampleTable').append(createRow());

            $('#btnAdd').click(function(){
                $('#sampleTable').append(createRow());
            });

            $('#btnSubmit').click(function(){
                submitValues();
            });
        });
    </script>
  </head>
  <body>
    <table id="sampleTable">

    </table>
    <button id="btnAdd">Add</button>
    <button id="btnSubmit">Submit</button>
  </body>
</html>  

Upvotes: 2

Related Questions