好的,如果选择了上一个选择框选项,我希望能够添加另一个具有相同选项的选择框。如果取消选择,则删除最后一个选项框w / options。
以下是我正在尝试的内容,我可以使用第一个选择框添加/删除另一个选择框,但我无法使用新创建的选择框。
var counter = 1; // as we already have the first dropdown
function populate(selector) {
$(selector)
.append('<option value="foo">foo</option>')
.append('<option value="bar">bar</option>')
}
populate('#select_options_1');
$("#select_options_" + counter).change( function() {
var addNewSelect = $(this).val() != '';
if(addNewSelect) {
counter++;
var newSelectOption = $(document.createElement('select')).attr("id", 'select_options_' + counter);
newSelectOption.html('<option value="">Please Select an Option</option>' +
'<option value="foo">foo</option>' +
'<option value="bar">bar</option>');
newSelectOption.appendTo("#select_option_groups");
} else {
$('#select_options_' + counter).remove();
if(counter > 1) {
counter--;
}
}
alert('Add New Select? ' + addNewSelect + ' Counter ' + counter);
});
HTML
<div name="select_option_groups" id="select_option_groups">
<select name="select_options_1" id="select_options_1">
<option value="">Please Select an Option</option>
</select>
</div>
上面的示例代码:http://jsfiddle.net/RaHhY/31/
答案 0 :(得分:1)
答案 1 :(得分:1)
这是一个较短的解决方案,不确定您是否感兴趣:
$(function(){
var counter = 2;
var onChange = function(e){
val = $(':selected',this).val() || '';
if (val != ''){
// they may be able to toggle between valid options, too.
// let's avoid that using a class we can apply
var c = 'alreadyMadeASelection';
if ($(this).hasClass(c))
return;
// now take the current select and clone it, then rename it
var newSelect = $(this)
.clone()
.attr('name','select_options_'+counter++)
.appendTo($(this).parent())
.change(onChange);
$(this).addClass(c);
} else {
var id = $(this).attr('name').match(/\d+$/), parent = $(this).parent();
$(this).remove();
// re-order the counter (we don't want missing numbers in the middle)
$('select',parent).each(function(){
var iid = $(this).attr('name').match(/\d+$/);
if (iid>id)
$(this).attr('name','select_options_'+(iid-1));
});
counter--;
}
};
$('#select_option_groups select').change(onChange);
});
鉴于以下内容:
<div id="select_option_groups">
<select name="select_options_1">
<option value="" selected>Please select an option</option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
</div>
<强> Demo 强>
对于更短的代码来说太多了:傻笑:无论如何,这是一个有一些基本改进的更新: