Thursday, December 27, 2012

Creating Dynamic Controls in JavaScript

Creating dynamic controls in javascript will provide us a great feature for our websites that too will give a flexible data entry pages.  For creating controls dynamically in javascript we can follow some basic rules like - Createing a method for creating a particular control.  We can use this method for creating that particular control in our whole project.

Creating controls in javascript can be done by using "document.createElement()" method by passing tag name as parameter as follows

for example if we want to create a textbox or some input fields, then the code will be as follows

var textBox = document.createElement('input');

then by adding setAttribute method for that control we can set various attributes for that control.

Here the code for this

Creating TextBox i.e., input text field:
function CreateTextBox(id, value) {
    var textBox = document.createElement('input');
    textBox.setAttribute("type", "text");
    textBox.setAttribute("value", value);
    textBox.setAttribute("id", id);
    return textBox;

Creating TextArea field:

function CreateTextArea(id, value) {
    var textarea = document.createElement('textarea');
    textarea.setAttribute('id', id);
    textarea.value = value;
    return textarea;

Creating button field i.e., input button field:
function CreateButton(id, value, Event) {
    var button = document.createElement('input');
    button.setAttribute('type', 'button');
    button.setAttribute('id', id);
    button.setAttribute('value', value);
    return button;

Finally, by using the "appendChile()" method we can add those controls as child controls for any parent like div or paragraph tags as follows

document.getElementById('div1').appendChild(CreateTextBox('txtTTitle', ''));

Happy Coding...