How to generate dynamic repeating controls and providing unique ids using HTML and JQuery?

Hi Folks,

It has been a long time, Hope everyone is doing great.

In this post I am writing about how to generate dynamic repeating controls and providing unique ids using HTML and JQuery. You will come to know how to create a multiple list of controls, that will be created when you click on add button, and then providing unique ids to them. I am assuming you have referenced JQuery libraries in your page already.Let us jump to the steps.

  • Inside the html body tag part, declare a div and give its id as “divDynamic”.

<span id=”btnAddNew”>Add New</span>

<div id=”divDynamic”></div>

  • Create another div that is set to display none and its id is going to be “divTemplateContainer”. This is going to have all the controls that are going to be repeated.

<div style=”display:none” id=”divTemplateContainer”>

<input type=”text” id=”textbox”/>

<input type=”text” id=”textbox1″/>

</div>

  • Now, we need to regenerate the controls on click of “Add New”. So, inside the script tag, write a Jquery click event for the btnAddNew, where fetch the inner html of the template and append it to the divDynamic. Once after appending pass the container id and index and replace the ids as given in the “GetElementInsideContainer” method.

<script>

var Index = 0;

$(“#btnAddNew”).click(function () {

var template= $(“#divTemplateContainer”)[0].innerHTML;
var domText = ‘<div id=”template’ + Index + ‘”></div>’;
if (template!= “”) {
$(“#divDynamic”).append(domText);
$(“#template” + Index ).append(template);
GetElementInsideContainer(“template” + Index , Index ); /*Call the action by passig the div id and the index*/
Index ++;
}

});

/*Change the ids within the template on the fly*/
function GetElementInsideContainer(containerID, index) {
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName(“*”);
for (var i = 0; i < elms.length; i++) {
if (elms[i].id) {
$(“#” + elms[i].id).attr(“id”, elms[i].id + index);
}
}
}

</script>

Hope the above steps saves your time. Happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s