2011-09-06 165 views
3

如何動態添加/刪除文本框(不清除文本框的數據)和相應的刪除按鈕上相應的刪除按鈕點擊事件通過javascript?Javascript添加/刪除文本框和相應的刪除按鈕

注意:每個動態創建的文本框都有單獨的按鈕。

以下是我的javascript功能。我使用jQuery 1.3.2

function addOption() 
{ 
     var d=document.getElementById("yash"); 
     d.innerHTML+="<input type='text' id='mytextbox' name='textbox' class='form-field medium' >"; 
     d.innerHTML+="<input type='button' id='mybutton' name='del'>";  
     $("#mybutton").click(function() { 
      $("#mytextbox").remove(); 
      $(this).remove(); 
     }); 
     d.innerHTML+="<br/>"; 

} 
+0

什麼ü由不清除文本框的數據是什麼意思?如果你刪除它肯定會去。你想刪除它還是隻隱藏它。 –

+0

我的意思是我不想清除文本框。我想刪除文本框也是相應的刪除按鈕,我點擊它刪除其核心指示文本框。 – Yash

回答

3

我做了一個非常簡單的例如你:http://jsfiddle.net/BHdhw/

你可以查NGE它適合你的需要,這裏是代碼:

HTML

<div class='Option'><input type='text' name='txtTest'/> <span class='Delete'>Delete</span></div> 

<br/><br/> 
<span class='Add'>Add Option</span> 

jQuery的

$(function(){ 

    $('.Delete').live('click',function(e){ 
    $(this).parent().remove(); 
    }); 
    $('.Add').live('click',function(e){ 
     $('.Option:last').after($('.Option:first').clone()); 
    }); 

}); 

注:在使用動態HTML工作,始終使用.live來綁定你的事件

UPDATE [檢索所有值]

鏈接例如如何檢索值:http://jsfiddle.net/BHdhw/1/

添加HTML

<span class='Retrieve'>Retrieve Values</span> 

新增jQuery的

$('.Retrieve').live('click',function(e){ 
     $('.Option input').each(function(i,e){ 
     alert($(e).val()); //Alerts all values individually 
     }); 
}); 
+0

我明白了,謝謝。 – Yash

+0

太棒了!不要忘記標記正確的答案,cheerz哥們 –

+0

現在我該如何回顧在這些文本框中輸入的值? – Yash

0

這裏是C omplete代碼...

<html> 
<head> 
    <title>Adding and Removing Text Boxes Dynamically</title> 
    <script type="text/javascript"> 
     var intTextBox=0; 
     //FUNCTION TO ADD TEXT BOX ELEMENT 
     function addElement() 
     { 
      intTextBox = intTextBox + 1; 
      var contentID = document.getElementById('content'); 
      var newTBDiv = document.createElement('div'); 
      newTBDiv.setAttribute('id','Hosp'+intTextBox); 
      newTBDiv.innerHTML = "Text "+intTextBox+": <input type='text' id='hospital_" + intTextBox + "' name='" + intTextBox + "'/> <a href='javascript:removeElement(\"" + intTextBox + "\")'>Remove</a>"; 
      contentID.appendChild(newTBDiv); 
     } 
     //FUNCTION TO REMOVE TEXT BOX ELEMENT 
     function removeElement(id) 
     { 

      if(intTextBox != 0) 
      { 
       var contentID = document.getElementById('content'); 
       //alert(contentID); 
       contentID.removeChild(document.getElementById('Hosp'+id)); 
       intTextBox = intTextBox-1; 
      } 
     } 
    </script> 
</head> 
<body> 
    <p>Demo of Adding and Removing Text Box Dynamically using JavaScript</p> 
    <p><a href="javascript:addElement();" >Add</a></p> 
    <div id="content"></div> 
</body>