根据选择下拉值,我动态添加一些文本字段。 我可以使用它,但是根据选择值,输入字段需要添加两倍。 因此,如果选择值等于1,则应添加2个输入字段。两个输入字段应具有不同的占位符值。
我可以在第一次加载页面时使用它。但是当我再次更改选择时,它会显示输入字段的数量减去2或减1.因此当选择值为2时,它会显示3或2个输入字段而不是4。
我看不出我做错了什么。非常感谢任何帮助。
<select name="custom[3426980]" id="graveren">
<option value="" data-amount="0" selected="selected">No thx!</option>
<option value="28714790" data-amount="1">Some value 1</option>
<option value="28714791" data-amount="2">Some value 2</option>
<option value="28714792" data-amount="3">Some value 3</option>
// etc etc....
</select>
<div id="steps"></div>
function addTextBoxes(){
var count = $('#graveren option:selected').data('amount');
$('#steps input:gt('+(count-2)+')').remove();
if(count !== 0){
for (var i = $('#steps input').length; i < count; i++){
var html = '<input type="text" placeholder="Bead '+(i+1)+' front" value="" /><input type="text" placeholder="Bead '+(i+1)+' back" value="" />'
$(html).appendTo('#graveren #steps');
}
} else {
$('#steps input').remove();
}
}
$(function(){
addTextBoxes();
$('#graveren select').on('change', function(){
addTextBoxes();
});
});
答案 0 :(得分:0)
问题出在这里:
$('#graveren select').on('change', function(){
addTextBoxes();
});
您正在寻找选择ID为#34; graveren&#34;的内部选择。只需将其更改为:
$('#graveren').on('change', function(){
我在这里发现了另一个问题:你将$(html).appendTo('#graveren #steps');
元素附加到id&#34; step&#34 ;,它嵌套到具有id&#34; graveren&#34;的元素。但是你没有带有id&#34;步骤&#34;你选择id&#34; graveren&#34; ...只需改变这一行:
$(html).appendTo('#graveren #steps');
为:
$(html).appendTo('#steps');
您的代码将有效......完整示例:
function addTextBoxes(){
var count = $('#graveren option:selected').data('amount');
$('#steps input:gt('+(count-2)+')').remove();
if(count !== 0){
for (var i = $('#steps input').length; i < count; i++){
var html = '<input type="text" placeholder="Bead '+(i+1)+' front" value="" /><input type="text" placeholder="Bead '+(i+1)+' back" value="" />'
$(html).appendTo('#steps');
}
} else {
$('#steps input').remove();
}
}
$(function(){
addTextBoxes();
$('select#graveren').on('change', function(){
addTextBoxes();
});
});
&#13;
<select name="custom[3426980]" id="graveren">
<option value="" data-amount="0" selected="selected">No thx!</option>
<option value="28714790" data-amount="1">Some value 1</option>
<option value="28714791" data-amount="2">Some value 2</option>
<option value="28714792" data-amount="3">Some value 3</option> </select>
<div id="steps"></div>
<script src="https://unpkg.com/jquery"></script>
&#13;
答案 1 :(得分:0)
问题在于逻辑本身。纠正了你的逻辑。看看它是否有帮助。
function addTextBoxes(){
var count = $('#graveren option:selected').data('amount');
var removeCount = 2*count-1;
$('#steps input:gt('+removeCount+')').remove();
if(count !== 0){
for (var i = $('#steps input').length/2; i < count; i++){
var html = '<input type="text" placeholder="Bead '+(i+1)+' front" value="" /><input type="text" placeholder="Bead '+(i+1)+' back" value="" />'
$(html).appendTo('#steps');
}
} else {
$('#steps input').remove();
}
}
$(function(){
addTextBoxes();
$('#graveren').change(function(){
addTextBoxes();
});
});