【发布时间】:2014-01-28 10:40:02
【问题描述】:
我正在尝试制作一个下拉菜单可以重复多次的表单,并且可以触发显示其后的表单补充。
感谢这个例子:Repeating div with form fields,我已经完成了复制,但是复制的菜单并没有触发表单隐藏部分的显示。我对 jquery 没有太多经验,所以我不确定我做错了什么。这是一个jsfiddle和代码:
jsfiddle:http://jsfiddle.net/jP8cW/2/
HTML
<form action="#" method="post">
<div class="repeatingSection">
<select id="j_id_1" name="j_id_1">
<option value="none">SELECT TITLE</option>
<option value="new">New title</option>
<option value="other">Other titles</option>
</select>
<div class="hidden">
<h3>New Journal Info</h3>
<p>
<label for="title">Title: </label>
<input type="text" name="j_title" id="title"/>
</p>
</div>
</div>
<a href="#" class="addJourn">Add Journal</a>
<p><input type="submit"/></p>
</form>
JS
$('.addJourn').click(function(){
var currentCount = $('.repeatingSection').length;
var newCount = currentCount+1;
var lastRepeatingGroup = $('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("select").each(function (index, select) {
select.id = select.id.replace("_" + currentCount, "_" + newCount);
select.name = select.name.replace("_" + currentCount, "_" + newCount);
});
newSection.find("label").each(function (index, label) {
var l = $(label);
l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
});
return false;
});
$("select[id^='j_id']").change(function(){
var selection = this.value; //grab the value selected
if (selection==="new"){
$(this).next('.hidden').show()
} else {
$(this).next('.hidden').hide()
}
});
CSS 就是 .hidden {display: none;}
非常感谢任何建议或见解。
【问题讨论】:
-
这看起来比你需要的代码多得多...考虑过使用
index?? -
只是出于好奇,为什么要复制
select?一个还不够吗? -
您还克隆了带有 ID 的元素,这将导致 重复的 ID 元素到处都是,这会给您带来问题。
-
@RokoC.Buljan 我试图基本上自动增加 ID,这一直适用于选择,但我错过了表单隐藏部分中的重复 ID。选择是重复的,因为它是内部购买跟踪应用程序的一部分,所以我希望人们能够说“我们购买了这个包含所有这些标题的订阅包”,将两者都输入数据库,因为购买和标题是分开的具有 M:N 关系的表。