twitter-bootstrap jQuery 动态添加表单域,删除表单域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18952410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Dynamic Add Form Field, Remove Form Field
提问by Johny Bravo
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
您好,从本教程中获得灵感后,我正在尝试添加新表单字段并删除表单字段 - http://bootsnipp.com/snipps/dynamic-form-fields
My Current Problem is to delete and reset the value of all in chronological order.
我当前的问题是按时间顺序删除和重置 all 的值。
<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 :-
父元素正在被移除,但下一个计数器未正确重置。以隐藏和所有新创建的形式:-
Only Add Demo :- http://bootsnipp.com/snipps/dynamic-form-fields
仅添加演示:- http://bootsnipp.com/snipps/dynamic-form-fields
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
添加带有错误的删除演示:- http://jsfiddle.net/6dCrT/2/
Can someone help me please.
有人能帮助我吗。
Thanks
谢谢
回答by Unknown
Try:
尝试:
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);
}

