需要一些帮助或指示才能实现以下目标。 单击时克隆输入字段并在更改时检索字段的值,以便将它们作为文本粘贴到另一个 div 中。然而,它似乎只适用于原始硬编码字段(不适用于克隆字段)。我尝试在代码中的多个位置添加每个函数,但没有成功。 我的代码现在看起来像这样:
<div class="cartWrapper">
<div class="clonedInput">
<label for="chipsCategory" class="">Chips Category <span class="requiredField">*</span></label>
<select class="categoryName1 changeFields" name="chipsCategory">
<option value="Kraks">Kraks</option>
<option value="Curls">Curls</option>
<option value="Crisps">Crisps</option>
</select>
<label for="chipsTaste" class="">Choose Taste <span class="requiredField">*</span></label>
<select class="chipsTaste1 changeFields" name="chipsTaste">
<option value="brand_1">Brand 1</option>
<option value="brand_2">Brand 2</option>
<option value="brand_3">Brand 3</option>
</select>
<label for="chipsQty">Quantity <span class="requiredField">*</span></label>
<input type="number" value="1" class="changeFields chipsQty" name="chipsQty[">
</div>
<button class="clone">Clone</button>
</div>
</div>
<div id="pasteItems"></div>
和js:
$( document ).ready(function() {
function clone(){
$('.clonedInput:first')
.clone()
.appendTo(".cartWrapper")
.each(function(){})
.on('click','button.clone',clone).append('<button class="remove">Remove</button>')
.on('click','button.remove',remove);
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
function getValues() {
var categoryName = $('.categoryName1').val();
var chipsTaste = $('.chipsTaste1').val();
var chipsQty = $('.chipsQty').val();
$('#pasteItems').text(categoryName + ' ' + chipsTaste + ' ' + chipsQty);
}
getValues();
$('.changeFields').change(function(){
$(this).each(function(){
getValues();
});
});
});
非常感谢您的帮助!
最佳答案
由于它们是动态创建的,因此无法以相同的方式选择它们 ( see Delegation )。所以你需要:
$(".cartWrapper").on('change', '.changeFields', function() {
//do what you need to with the value of the cloned input
});
关于jQuery,获取所有克隆输入字段的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017535/