2012-03-19 35 views
0

我使用的表單可以選擇添加更多城市以輸入多個城市名稱。有一個按鈕t0也刪除字段。 它工作完美,但問題出在下面的代碼我得到的第一個城市的刪除按鈕也是不正確的。爲表單中的多個輸入字段添加/刪除選項

那麼如何從第一組輸入框中刪除'刪除'按鈕。刪除按鈕應該繼續爲所有新生成的字段。

我從本網站http://www.quirksmode.org/dom/domform.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Extending forms</title> 
    <script type="text/javascript" src="./Javascript - Extending forms_files/quirksmode.js"></script> 
    <script type="text/javascript"> 
    <!-- 
    var counter = 0; 

    function init() { 
     document.getElementById('moreFields').onclick = moreFields; 
     moreFields(); 
    } 

    function moreFields() { 
     counter++; 
     var newFields = document.getElementById('readroot').cloneNode(true); 
     newFields.id = ''; 
     newFields.style.display = 'block'; 
     var newField = newFields.childNodes; 
     for (var i=0;i<newField.length;i++) { 
      var theName = newField[i].name 
      if (theName) 
       newField[i].name = theName + counter; 
     } 
     var insertHere = document.getElementById('writeroot'); 
     insertHere.parentNode.insertBefore(newFields,insertHere); 
    } 

    // --> 
    </script> 
    </head> 

    <body> 

<!--This prat will be dynamically generated on clicking the add more button (and this is the default one to be shown in the page)--> 
    <div id="readroot" style="display: none"> 
    <input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"> 
     <label for="city">City:</label> &nbsp;&nbsp;<input type="text" class="pssng1" name="city" value="" />&nbsp;&nbsp; 
     <label for="days">Days:</label> <input type="text" class="pssng1" name="days" value="" /> 
    </div>  
<!--This prat will be dynamically generated on clicking the add more button--> 

    <form method="post" > 
    <div id="" style="display: block; "></div> 
    <span id="writeroot"></span> 
    <input type="button" id="moreFields" value="Add more!"> 
    </form> 

    </body> 
    </html> 

回答

1

修改JavaScript喜歡得到這個代碼;

<script type="text/javascript"> 
    <!-- 
    var counter = 0; 

    function init() { 
     document.getElementById('moreFields').onclick = moreFields; 
     moreFields(); 
    } 

    function moreFields() { 
     counter++; 
     var newFields = document.getElementById('readroot').cloneNode(true); 
     newFields.id = ''; 
     newFields.style.display = 'block'; 
     var newField = newFields.childNodes; 
     for (var i=1;i<newField.length;i++) { 
      var theName = newField[i].name 
      if (theName) 
       newField[i].name = theName + counter; 
     } 
     var insertHere = document.getElementById('writeroot'); 
     insertHere.parentNode.insertBefore(newFields,insertHere); 
    } 

    // --> 
    </script> 
相關問題