本文介绍了jQuery动态添加表单字段,删除表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我在从本教程中获得启发后,尝试添加新的表单字段并删除表单字段- http://bootsnipp.com/snipps/dynamic-form-fields
Hello I am trying to add new form field and delete form field after getting inspired from this tutorial - http://bootsnipp.com/snipps/dynamic-form-fields
我当前的问题是按时间顺序删除并重置所有值.
My Current Problem is to delete and reset the value of all in chronological order.
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Nice Multiple Form Fields</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8"
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
</div>
<br /><small>Press + to add another form field :)</small>
</div>
</div>
JavaScript:-
Javascript :-
var next = 1;
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
父元素将被删除,但下一个计数器未正确重置.以隐藏的和所有新创建的形式:-
Parent Element is getting removed, but next counter is not reset properly. in hidden and all new created form :-
仅添加演示:- http://bootsnipp.com/snipps/dynamic-form-fields
添加带有错误的删除演示:- http://jsfiddle.net/6dCrT/2/
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
有人可以帮我吗?
谢谢
推荐答案
尝试:
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
var newInput = $(newIn);
console.log(addto);
$(addto).after(newInput);
if(next>1)
$("button#b"+next).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
这篇关于jQuery动态添加表单字段,删除表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!