Add input fields to div container (javascript)

时光毁灭记忆、已成空白 提交于 2020-01-22 16:55:45

问题


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.


回答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);
}



回答2:


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

So something like

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


来源:https://stackoverflow.com/questions/9455066/add-input-fields-to-div-container-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!