Jquery 将复选框值填充到动态创建的下拉列表中时出现问题
我有两个复选框,当我选中它们时,我希望选中的数据进入下拉选择框。我已经写了这样的代码Jquery 将复选框值填充到动态创建的下拉列表中时出现问题,jquery,html,Jquery,Html,我有两个复选框,当我选中它们时,我希望选中的数据进入下拉选择框。我已经写了这样的代码 <input type="checkbox" name="conditions[]" value="1">Sample 1 <input type="checkbox" name="conditions[]" value="2">Sample 2 <select name="Control[]"></select> <script> jQue
<input type="checkbox" name="conditions[]" value="1">Sample 1
<input type="checkbox" name="conditions[]" value="2">Sample 2
<select name="Control[]"></select>
<script>
jQuery(function ($) {
var $conds = $('input[name="conditions[]"]'),
$ctrl = $('select[name="Control[]"]');
$conds.change(function () {
if (this.checked) {
$('<option />', {
value: this.value,
text: this.nextSibling.nodeValue
}).appendTo($ctrl)
} else {
$ctrl.find('option[value="' + this.value + '"]').remove();
}
})
})
</script>
示例1
样本2
jQuery(函数($){
var$conds=$('input[name=“conditions[]”]),
$ctrl=$('select[name=“Control[]”]);
$conds.change(函数(){
如果(选中此项){
$('', {
value:this.value,
文本:this.nextSibling.nodeValue
}).appendTo($ctrl)
}否则{
$ctrl.find('option[value=“”+this.value+'“]').remove();
}
})
})
这对我来说很好,但数据并没有填充在附加的下拉选择框中
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<p></p><div class="new_wrapper"> <select name="Control[]"></select><p></p><center><a href="javascript:void(0);" class="btn btn-danger btn-sm text-center remove_button" >Remove Package</a></center></div>';
var x = 1;
$(addButton).click(function() {
if(x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
});
var addButton=$('.add_按钮');
var wrapper=$('.field_wrapper');
var fieldHTML='';
var x=1;
$(添加按钮)。单击(函数(){
如果(x
您正在动态添加新的选择框。加载文档时,未将这些新添加的选择框作为$ctrl=$('select[name=“Control[]”])
的一部分进行选择。因此,每当插入新的选择框时,都需要更新选择。您可以通过在addbutton
单击处理程序中插入行$ctrl=$('select[name=“Control[]”)
(在包装中附加新的选择框之后)来完成此操作。希望这有帮助
$(addButton).click(function() {
if(x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
// INSERT THIS LINE. THIS WILL SELECT THE NEWLY INSERTED ELEMENTS TOO
$ctrl = $('select[name="Control[]"]');
});
$(添加按钮)。单击(函数(){
如果(x
您正在动态添加新的选择框。加载文档时,未将这些新添加的选择框作为$ctrl=$('select[name=“Control[]”])
的一部分进行选择。因此,每当插入新的选择框时,都需要更新选择。您可以通过在addbutton
单击处理程序中插入行$ctrl=$('select[name=“Control[]”)
(在包装中附加新的选择框之后)来完成此操作。希望这有帮助
$(addButton).click(function() {
if(x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
// INSERT THIS LINE. THIS WILL SELECT THE NEWLY INSERTED ELEMENTS TOO
$ctrl = $('select[name="Control[]"]');
});
$(添加按钮)。单击(函数(){
如果(x
@NicoHaase添加了解释。希望如此helps@NicoHaase补充说明。希望这有帮助