Hi,
In this article we will discuss about the Basics in Dynamic Controls programming in JavaScript.
We will also discuss about syntax and symantics of the JavaScript methods required to achieve this task.
After the completion of this session - you are able to:
1) Identify the HTML Tag and its elements
2) Identify and use the JavaScript methods for
a) Creating the elements dynamically
b) Setting properties for the dynamically created elements
c) Attaching the dynamically created element to an existing control
Section-I :: Basics :
We can add controls dynamically to a HTML element which can be represented in the form of a tag.
Let us consider the following tag syntax
< tagname attribute1="value1" attribute2="value2" ... attributeN="valueN" / >
Description:
tagname : HTML tagname like INPUT, TABLE, TR, TD ... etc.,
attribute : Attributes helps to describe the tag like what is its id, name, style ... etc.,
value : Values can be any literal.
Note: It is safe to enclose literal values in double-quotation-marks while assigning to attributes eventhough it is optional.
For example consider the tag below:
< input type="hidden" id="hdnSample" name="hdnSample" value="This is Hidden Value" />
Here
TagName : input
Attribute/Value Pairs:
(1) type/"hdnSample"
(2) id/"hdnSample"
(3) name/"hdnSample"
(1) value/"This is Hidden Value"
Section-II :: JavaScript Methods :
createElement Method :
This method is used to create new HTML elements dynamically.
Syntax: NewObject = ExistingObject.createElement("Tag-Name");
Where
(*) "Tag-Name" :: represents the controls tag-name like "input" for textbox, "select" for dropdown list, ... ,etc.,
Example:
var objNewObject = document.createElement("input");
The above example creates a new "input" tag and assigns to objNewObject.
Note: The newly created object will not reflect anywhere until its been assigned using "appendChild" method.
Reference :: http://msdn.microsoft.com/en-us/library/ms536389.aspx
appendChild Method :
This method is used to add the newly created object to an existing object collection.
Syntax: parentObject.appendChild("NewObject");
Where
(*) "NewObject" :: Is the variable representing the newly created object.
Example: document.appendChild(objNewObject);
The above example appends the contents of the objNewObject to the document object.
Once appended it gets created and can be accessed from other functions like statically created objects.
Reference :: http://msdn.microsoft.com/en-us/library/ms535934(VS.85).aspx
setAttribute Method :
This method is used to append attributes to the HTML objects.
Syntax: objNewObject.setAttribute("attribute","value");
Where
(*) "attribute" :: The property name
(*) "value"" :: The property value
Example:
objNewObject.setAttribute("type","text");
objNewObject.setAttribute("id","txtName");
The above example assings the "type" and "text" attributes to the objNewObject.
Reference :: http://msdn.microsoft.com/en-us/library/ms536739(VS.85).aspx