简体   繁体   English

我的JavaScript出现问题,添加了更多输入字段,文本字段中的值将无法保留

[英]I have trouble with my javascript with add more input fields, values inside text fields won't retain

 <div id="addmore">
    <ul class="jcform" id="countme">
        <li><strong>Criteria Name</strong></li>
        <li><strong>Points</strong></li>
        <li>&nbsp;</li>
    </ul>
    <ul class="jcform" id="countme">
        <li><input class="form-control" name="cname[]" type="text"/></li>
        <li><input class="form-control" name="cpoints[]" type="text"/>  </li>
        <li>&nbsp;</li>
    </ul>
 </div>
 <input class="btn btn-primary" type="button" onclick="addmore()" value="+ add more field" />

I have the above code and javascript: 我有上面的代码和javascript:

function removeme(numm) {
    document.getElementById('remove'+numm+'').style.display = 'none';
      } 
function addmore() {    
    var top_level_div = document.getElementById('addmore');
    var count = top_level_div.getElementsByTagName('ul').length;        
    var tbl1 = '<ul class="jcform" id="remove'+count+'" style="display:block">
    <li>
        <input class="form-control" id="field1" name="cname[]" type="text" value=""/>
    </li>
    <li>
        <input class="form-control" id="fieldpoints1" name="cpoints[]" type="text" value=""/>
    </li>
    <li><a href="#" class="btn btn-warning" onclick="removeme('+count+')">Removed</a>
    </li></ul>';    

    document.getElementById('addmore').innerHTML += tbl1    
 }

My problem is that when i enter values in the text fields and then click on the 'add more field' button to add more input fields, the values i've entered textfields won't retain and i have to type it again. 我的问题是,当我在文本字段中输入值,然后单击“添加更多字段”按钮以添加更多输入字段时,我输入的文本字段的值将不会保留,我必须再次输入。 I don't know why. 我不知道为什么 Can someone please tell me why? 有人可以告诉我为什么吗? and how to retain the values in the text fields if i click on the add more button. 以及如果我单击添加更多按钮,如何在文本字段中保留值。 Thanks. 谢谢。

Because everytime you are overwritting the container html replacing the existing elements 因为每次您改写容器html替换现有元素时,

function addmore() {
    var top_level_div = document.getElementById('addmore');
    var count = top_level_div.getElementsByTagName('ul').length;
    var ul = document.createElement('ul');
    ul.className = 'jcform';
    ul.id = 'remove' + count;
    var tbl1 = '<li><input class="form-control" id="field1" name="cname[]" type="text" value=""/></li>  <li><input class="form-control" id="fieldpoints1" name="cpoints[]" type="text" value=""/></li><li><a href="#" class="btn btn-warning" onclick="removeme(' + count + ')">Removed</a></li>';
    ul.innerHTML = tbl1;

    document.getElementById('addmore').appendChild(ul)
}

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM