2

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.

2 Answers 2

7

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

So something like

document.getElementById('addlist').appendChild(text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.