简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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