jQuery的动态添加表格字段,删除表格字段
问题描述:
你好我试图从本教程中得到启发后添加新的表单字段和删除表单字段 - http://bootsnipp.com/snipps/dynamic-form-fieldsjQuery的动态添加表格字段,删除表格字段
我目前的问题是删除并重新设置所有的值按时间顺序排列。
<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: -
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);
}
父元素是越来越删除,但下一个计数器不能正确复位。在隐藏和所有新创建的窗体: -
只添加演示: - http://bootsnipp.com/snipps/dynamic-form-fields
添加删除演示与错误: - 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);
}
但字段值没有得到复位。添加3个字段并删除2个其他字段后..下一个字段仍然带有数字'field4':( –
@JohnyBravo为什么你想要改变元素属性,如ID,名字?你仍然可以解析父div的所有输入内 – Unknown
请原谅我的noobness,你能解释一下你的意思吗? –