January 1st, 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 id="holder">

There are five buttons to add simple text, textbox, checkbox, radio and normal button.
See following jQuery code to add controls in holder division:

var $ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'}).addClass("text");
var $ctrl = $('<input/>').attr({ type: 'checkbox', name:'chk'}).addClass("chk");
var $ctrl = $('<input/>').attr({ type: 'radio', name:'rad'}).addClass("rad");
var $ctrl = $('<input/>').attr({ type: 'button', name:'btn',value:'Button'}).addClass("btn");
var lbl = prompt ("Enter Text","");

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.

  • something like this:

    .text(‘Select a city / town in Sweden’)

  • You can id easily similar to name, see following:
    var $ctrl = $(”).attr({ type: ‘button’, id : ‘myID1′, name:’btn’,value:’Button’}).addClass(“btn”);

  • Dave Seavey

    I’ve been working with jQuery for a couple years but only recently began using it to generate dynamic markup. This is the best explanation of how to create dynamic forms that I’ve found. Excellent work, and thanks for taking the time to share your knowledge! 

  • Khalidusman30

    Please do u have any source code how to add this jquery to the page and what else we need to add each button click…khalidusman30@yahoo.com

  • Khalidusman30

    Please code you place the source code for this article

  • kriti gupta

    how to add radio groups dynamically?

  • Gopichand

    This might be an old post but good idea of creating controls in jquery. I am new to mvc am working on mvc4 i want to add controls in view and when click on save pass the data to controller to save it in DB. what i need is how to pass the holder div data to controller. Thanks in advance.

  • md javed

    how to add data into database using this form