Monday 11 March 2013

JQuery to add html controls dynamically during runtime

I want to add a textbox controls dynamically during runtime. At the same time I should be able to remove the added controls one by one. Below is the JQuery to achieve the same. For the below script to run I will need the reference of the jquery-1.3.2.min.js file.

<script type="text/javascript" src="Path/jquery-1.3.2.min.js"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function () {
var counter = 2;
$("#addtextarea").click(function () {
if (counter1 > 5) {
alert("Only 5 textboxes are allowed");
return false;
}
else
 {
var newTextAreaDiv = $(document.createElement('div')).attr("id", 'TextAreaDiv' + counter);
newTextAreaDiv.after().html('<textarea name="TextArea' + counter + '" id=" TextArea ' + counter + '" value="" ></textarea><br/><br/>');
newTextAreaDiv.appendTo("#TextGroup");
counter++;
}
});
$("#removetextarea").click(function () {
if (counter == 2) {
alert("No more textbox to remove");
return false;
}
else
 {
 counter1--;
 $("#TextAreaDiv" + counter).remove();
 }
 });
 });
 </script>


The above script will check the ID’s of DIV tags & accordingly add/remove the controls i.e. the new DIV tags inside the main DIV group. On click on the “Add” anchor tag the new DIV tag is created & the control inside the DIV tag is added & this DIV tag is added in the DIV Group one below the other. Same way the “Remove” anchor tag will remove the DIV tags with its controls in decending order one by one. Here while adding the controls I have restricted the user to add controls upto 5.


<div id="TextGroup">
    <div id="TextAreaDiv">
        <textarea name="TextArea" id=" TextArea "></textarea>
        <br />
    </div>
</div>
<div>
    <a id="addtextarea" href="#">Add</a>&nbsp;/&nbsp;<a id="removetextarea" href="#">Remove</a>
</div>

No comments:

Post a Comment