Sunday, November 28, 2010

Jquery - Dynamically add TextBox and Consolidate Text Data for Server Submission

Intro:
A function that allows user to add new TextBox (on demand) and then when submit, all Textbox data is consolidated and hidden form field value set to the consolidated Data.

The HTML:

Type your Questions and click on 'add question' to add more ratings question.
<div>
    <div id="divTextBox">
        Question No. 1 <input type="text" id="txt_1" class="svTxt" size="80" />
    </div>

    <br />
        <a href="#" id="addQuestionLink">[ + ] Add Question</a>
</div>

<hr />

<div id="DebugSection">
        <asp:HiddenField ID="hdnData" runat="server" />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit To Server" />
        <hr />
        Server reads the hidden field and writes :<br /> <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</div>


The JQuery:
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        var txtCount = 1; //By default there is only 1 text box
        var svTextAll = ''; //consolidated questions


        //
        // Click ADD QUESTION function
        //  On span '#addTxt' click
        //
        $("#addQuestionLink").bind("click", function (e) {
            txtCount++;
            $("#divTextBox").append("<br />Question No. " + txtCount + " <input type='text' id='txt_" + txtCount + "' class='svTxt' size='80' />");
        });


        //
        // Click Submit button
        // Consoldate quesitons and updates the hidden form field value and
        //  postback to server for .cs to process
        //

        $("#btnSubmit").bind("click", function (e) {
            $(".svTxt").each(function (i) {
                svTextAll = svTextAll + '<|>' + $(this).attr('value');
            });

            //write data to hidden field.
            $("#hdnData").val(svTextAll);
        });

    });
    </script>

No comments: