Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Adding Form Elements dynamically in Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.43k
    Comment on it

    You can use JavaScript to add elements like textbox, button, radio button in a html form. createElement() method is used to create html elements at runtime.

    Here is the example:
    HTML:

    <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">add Button</option>
        <option value="text">add Textbox</option>
        <option value="radio">add Radio</option>
    </select>
    
    <input type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
    
    <span id=elementContent>&nbsp;</span>
    
    </form>

    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 cont = document.getElementById("elementContent");
    
        //Append the element in page (in span).
        cont.appendChild(element);
    
    }

    In the above example, we have a select box with the options to add button, textbook or radio button. When user makes a choice the element will be added in the form.
    we have used createElement() to create html elements and setAttribute to assign the different attributes to the dynamically created elements.

    You can check the demo here.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: