我有这个现有代码,我对此有一些帮助:http://jsfiddle.net/975VQ/11/
此代码的问题是我还想允许他们删除原始字段。我无法删除原始文本字段并仍然添加另一个文本字段。
有人可以告诉我如何解决这个问题吗?我假设它是通过使用 javascript 添加第一个条目,然后使用 javascript 每次添加标记而不是克隆它。
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#addfield"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
对此的任何帮助或意见将不胜感激。
最佳答案
您要删除原始字段上带有 id=InputsWrapper 的字段,即您要附加新闻字段的 div。
您需要将原始字段放在其他div中。
<div id="InputsWrapper">
<div>
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="removeclass">Delete</button>
</div>
</div>
关于javascript - 使用jquery动态添加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23290400/