Jan 01, 2011

Add controls (textbox, radio, checkbox..) dynamically in jQuery way

Generally, it is required to add elements like button, textbox, checkbox,radio ..etc dynamically in html form. This article explains how to add form elements dynamically in jQuery way. Let us take an example. Suppose we have to add controls on button click. See following HTML code:


<div style="display:inline">
<input type="button" id="txtPlain" value="Add Plain Text" style="" />
<input type="button" id="txt" value="Add TextBox" style="" />
<input type="button" id="chk" value="Add CheckBox" style="" />
<input type="button" id="rad" value="Add Radio" style="" />
<input type="button" id="btn" value="Add Button" style="" />
</div>
<div id="holder">
</div>

There are five buttons to add simple text, textbox, checkbox, radio and normal button.

See following jQuery code to add controls in holder division:


$(document).ready(function(){
$("#txt").click(function(){
var $ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'}).addClass("text");
$("#holder").append($ctrl);
});
$("#chk").click(function(){
var $ctrl = $('<input/>').attr({ type: 'checkbox', name:'chk'}).addClass("chk");
$("#holder").append($ctrl);
});
$("#rad").click(function(){
var $ctrl = $('<input/>').attr({ type: 'radio', name:'rad'}).addClass("rad");
$("#holder").append($ctrl);
});
$("#btn").click(function(){
var $ctrl = $('<input/>').attr({ type: 'button', name:'btn',value:'Button'}).addClass("btn");
$("#holder").append($ctrl);
});
$("#txtPlain").click(function(){
var lbl = prompt ("Enter Text","");
$("#holder").append(lbl);
});
});

It is done in jQuery way. The fastest way is to create control using $(document.createElement('input')) because

$('<input/>') uses document.createElement.

Hope, It helps.