当前,它仅将值相加一次。我有一个下拉列表(在此示例中,它只是您可以手动更改的输入值),我会不时更改。单击“添加”按钮时,它应将这些值带到field_wrapper上,同时动态添加新的输入字段以携带每个值。
意思是,我希望它添加从“文本”中选择的每个新值,并附加到每个新的输入文本字段!
我在函数上方设置了全局变量。但不确定为什么该值只显示一次,而每次单击“添加”时都不会添加新值
我希望这是有道理的!
JavaScript
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" id="test" value=""/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartD+ cartP;
$(wrapper).append(field)
$('#test').val(text)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
HTML
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
</div>
答案 0 :(得分:2)
要做更多的事情只是简单地插入html并将text
变量添加为id="test"
的值,但是最好使用class而不是id。
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartd + cartP;
$(wrapper).append(`<div><input type="text" id="test" value="${text}"/><a href="javascript:void(0);" class="remove_button"><img src="remove-icon.png"/></a></div>`)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
<button class="add_button">Add</button>
</div>