Add input fields to div container (javascript)

28,855

Solution 1

innerHTML changes reset form elements. Instead use appendChild. See this demo http://jsfiddle.net/5sWA2/

function addInput(id) {

    var addList = document.getElementById('addlist');
    var docstyle = addList.style.display;
    if (docstyle == 'none') addList.style.display = '';

    addid++;

    var text = document.createElement('div');
    text.id = 'additem_' + addid;
    text.innerHTML = "<input type='text' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput(" + addid + ")' id='addlink_" + addid + "'>add more</a>";

    addList.appendChild(text);
}

Solution 2

Take a look at this http://reference.sitepoint.com/javascript/Node/appendChild

So something like

document.getElementById('addlist').appendChild(text);
Share:
28,855
reggie
Author by

reggie

Updated on February 27, 2020

Comments

  • reggie
    reggie about 4 years

    I want to add some html data to the end of a div container. Currently, I do it with using innerHtml:

    <script language="javascript">
    var addid = 0;
    
    function addInput(id){
        var docstyle = document.getElementById('addlist').style.display;
        if(docstyle == 'none')
            document.getElementById('addlist').style.display = '';
    
        addid++;
    
        var text = "<div id='additem_"+addid+"'><input type='text' size='100' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput("+addid+")' id='addlink_"+addid+"'>add more</a></div>";
    
        document.getElementById('addlist').innerHTML += text;
    }
    </script>
    
    <div id="addlist" class="alt1" style="padding:10px;">
        New list items are added to the bottom of the list.
        <br /><br />
    </div>
    

    The problem is that the value that was entered in the input fields is removed once another input field is added. How can I add content without and keep the entered data?

    PS: I do not use jquery.