2011-09-06 123 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>