Saturday 25 August 2012

Adding HTML control dynamically using JQuery

In this article I will explain how to add HTML control dynamically using jQuery and then retrieve values from the dynamically generated controls.

You have seen many website where you find provision to add multiple mobile numbers, interests, subject or some other type of data by clicking Add button (this add new row with required fields).

In many websites this is done using Ajax ( i.e. control generated on server side and then rendered asynchronously on the client browser). The drawback of this is every time async postback happen to server and this overhead, also in some website the browser become very slow in cases it hang as well after 15-20 postbacks.

Well in jquery it is wery simple just by using appent method you can add the new DOM element inside existing DOM element like <div>.

Code to add HTML control

HTML:

<div id="mynewDiv" style="width:auto; height:auto"></div>
<input type="button" value="Add Mobile Number" id="btnNew"/>&nbsp;
<input type="button" value="Check Values" id="btnCheck"/>


JavaScript (jQuery):

$("#btnNew").click(function () {
    $("#mynewDiv").append("<div style='padding: 5px 5px 5px 5px;'><label>Mobile Number: </label>&nbsp;<input  type='text' width='200px' class='txtTelephone' /></div>")
});


In above code on clicking of "Add Mobile Number" button a new textbox with label is added to "mynewDiv" panal.
Now to read the values from the textbox added dynamically use below code:

$("#btnCheck").click(function () {
    $(".txtTelephone").each(function (i) {
        alert($(this).val());
    });
});


The complete javascript code look like:

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnNew").click(function () {
            $("#mynewDiv").append("<div style='padding: 5px 5px 5px 5px;'><label>Mobile Number: </label>&nbsp;<input  type='text' width='200px' class='txtTelephone' /></div>")
        });

        $("#btnCheck").click(function () {
            $(".txtTelephone").each(function (i) {
                alert($(this).val());
            });
        });
    });
</script>

No comments :