如何通过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 :(得分:3)
此代码适用于它:
$("#myButton").click(function () {
$("#myTextBox").remove();
$(this).remove();
});
看看: http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/
此致
答案 1 :(得分:3)
我为你做了一个非常简单的例子:http://jsfiddle.net/BHdhw/
您可以根据需要进行更改,以下是代码:
<强> 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
来绑定您的活动
更新[检索所有值]
链接示例如何检索值: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
});
});
答案 2 :(得分:0)
这是完整的代码......
<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>