我有一组两个选择框,我可以通过按下按钮来克隆它"添加更多"。问题是,组合不能再次使用。所以,如果我在第一个选择"Book"
而在第二个选择"Classic"
,我就不能再选择它了。
在此处查看演示:DEMO
HTML:
<div class="box">
<select name="area_id[1]" id="area_id_1" class="area">
<option value="0" disabled selected>Select an area...</option>
<option value="1" >Literature</option>
<option value="2" >Music</option>
<option value="3" >Cinema</option>
</select>
<select name="genre_id[1]" id="genre_id_1" class="genre">
<option value="0" disabled selected>Select a genre...</option>
<option value="1" >Classic</option>
<option value="2" >2000+</option>
<option value="3" >Portuguese</option>
</select>
<hr>
</div>
<span class="add">Click to Add More</span>
jQuery的:
var attrs = ['id'];
function resetAttributeNames(section, action) {
var index = section.prevAll('.box').length;
var tags = section.find('select'), idx = index + 1;
tags.each(function() {
var $this = $(this);
if(action === 'add'){
$this.find('option[value="0"]').attr('disabled', true);
$this.find('option[value="0"]').attr('selected', true);
}
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
var name = $this.attr('name');
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx)));
$this.attr('name', name.replace(/\[(.*?)\]/, '['+idx+']'));
}
});
});
}
$('.add').click(function(e){
e.preventDefault();
var lastRepeatingGroup = $('.box').last();
var cloned = lastRepeatingGroup.clone(true);
cloned.insertAfter(lastRepeatingGroup);
resetAttributeNames(cloned, 'add');
});
我尝试了什么:
$('.box').change(function() {
var this_id = $(this).attr('id');
var this_pos = getNumber($(this).attr('name'));
$('.area').each(function(){
var other_select_pos = getNumero($(this).attr('name'));
if($('#area_id_'+other_select_pos).val() === $('#'+this_id).val()){
var unselectable = $('#genre_id_'+other_select_pos).val();
$('#genre_id_'+this_pos+' option').each(function() {
if($(this).val() === unselectable){
$(this).attr('disabled', true);
}
});
}
})
})
function getNumber(name){
var regExp = /\[([^)]+)\]/;
var matches = regExp.exec(name);
return matches[1];
}
但是这个代码看起来似乎错了,而且它不能正常工作。我怎样才能干净利落地干净?
提前致谢