"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Wednesday, March 30, 2011

Dynamically adding HTML controls using javascript

Hi *.*,
yesterday ,I login to my facebook account and doing some timepass there. then i notice there are doing everything with out postback. Then i goto ViewSource option... Holly fuck.. Really shocked full JavaScript from top to bottom.Then my interest change how they... basic is Dynamically creating everything they need in JavaScript!!!!!.I'm not showing how they are, but the basic of that is this.as per some tips from developers.facebook.com.

Adding Elements like textbox, button, radio button etc in a html form using JavaScript is very simple. JavaScript’s document object has a method called createElement() which can be used to create html elements dynamically

source code


<html>
<head>
    <title>Dynamically add Textbox, Radio, Button in html Form using JavaScript</title>

    <script language="javascript">
        function add(type) {

            //Create an input type dynamically.
            var element = document.createElement("input");

            //Assign different attributes to the element.
            element.setAttribute("type", type);
            element.setAttribute("value", type);
            element.setAttribute("name", type);

            var foo = document.getElementById("fooBar");

            //Append the element in page (in span).
            foo.appendChild(element);

        }
    </script>

</head>
<body>
    <form>
    <h2>
        Dynamically add element in form.</h2>
    Select the element and hit Add to add it in form.
    <br />
    <select name="element">
        <option value="button">Button</option>
        <option value="text">Textbox</option>
        <option value="radio">Radio</option>
    </select>
    <input type="button" value="Add" onclick="add(document.forms[0].element.value)" />
    <span id="fooBar">&nbsp;</span>
    </form>
</body>
</html>



hope this helped u. Stay Tune...
Have a nice day... 'N happy Coding :)

No comments: