Tuesday, July 9, 2013

Dynamically create input fields - jQuery

JQuery Provides,  to add or remove a textbox dynamically. The idea is very simple,  jQuery createElement(), html() and remove() method. See below given example : 


<html>


<head>
    <title>Dynamically create input fields - jQuery</title>
    <script src="/js/jquery-1.4.js"></script>
    <link rel='stylesheet' type='text/css' href='/styles.css'>
    <script type="text/javascript">
        var i;
        $(function() {
            var addDiv = $('#addinput');
            i = $('#addinput p').size() + 1;
            $('#addNew').live('click', function() {
            $('<p><input type="text" id="p_new" size="40" name="p_new_' + i + '" value="" placeholder="I am New" /><a href="#" class="mybutton" id="remNew">Remove</a> </p>').appendTo(addDiv);
                i++;
                return false;
            });

            $('#remNew').live('click', function() {
                if (i > 2) {
                    $(this).parents('p').remove();
                    i--;
                }
                return false;
            });
        });
        function fillHiddenField() {
            $('#MyTextBoxLength').val(i);
            return true;
        }
    </script>

</head>
<body>
<%
If request("Submit") <> "" Then

    dim iCount : iCount = Request("MyTextBoxLength")
    For i = 0 to (iCount-1)
      Response.Write  Request("p_new_"&i) &"<br/>"
    Next
    
End If
 %>
    <h2>
        Dynammically Add Another Input Box</h2>
<form id="two" name="two" class="asholder" action="test1.asp" method="post">
    <div id="addinput" class="ui-button-global">
        <p>
            <!--<input type="text" id="p_new" size="20" name="p_new" value="" placeholder="Input Value" /><a
                href="#" id="addNew">Add</a>-->
            <a href="2013-rashiphal-in-hindi.asp" id="addNew" class="ui-button icon arrowright">
            Add</a>
        </p>
        <input type="hidden" name="MyTextBoxLength" id="MyTextBoxLength" value="" />
    </div>
    <input type="submit" class="mybutton" name="Submit" value="Get Result" onclick="return fillHiddenField();" />
</form>    
</body>
</html>


No comments:

Post a Comment