Monday, July 28, 2014

Dynamically creating html controls like textbox, labels using JavaScript

HI in this post i will show how to create html controls dynamically using JavaScript:

Below is the sample code :

Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function load() {
           
            var t = document.createElement("table"),
            tb = document.createElement("tbody"),
            tr = document.createElement("tr"),
            td = document.createElement("td");

            t.style.width = "100%";
            t.style.borderCollapse = 'collapse';

            var itemLabel = document.createElement("Label");
            itemLabel.innerHTML = "Enter Name";
            itemLabel.htmlFor = "txtName";
            td.appendChild(itemLabel);  
            tr.appendChild(td);
            tb.appendChild(tr);
            t.appendChild(tb);

            document.getElementById("divContent").appendChild(t);

            var t1 = document.createElement("table"),
            tb1 = document.createElement("tbody"),
            tr1 = document.createElement("tr"),
            td1 = document.createElement("td");

            t1.style.width = "100%";
            t1.style.borderCollapse = 'collapse';

            var element = document.createElement("input");
            element.setAttribute("type", "text");
            element.setAttribute("value", "");
            element.setAttribute("name", "Name");
            element.setAttribute("style", "width:200px");
            element.setAttribute("id", "txtName");
       
            td1.appendChild(element);
            tr1.appendChild(td1);
            tb1.appendChild(tr1);
            t1.appendChild(tb1);

            document.getElementById("divContent").appendChild(t1);

        }
    </script>
</head>
<body onload="load()">
    <form id="form1" runat="server">
   <div id="divContent"></div>
    </form>
</body>
</html>

Output:



No comments:

Post a Comment