我有一组两个选择框,我可以通过按“添加更多”按钮来克隆它。问题是,该组合无法再次使用。因此,如果我在第一个选项上选择 “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];
}
但是这段代码看起来很错误,并且无法正常工作。我怎样才能简单干净地做到这一点?
提前致谢
最佳答案
您想要绑定(bind)onchange
事件select
并查看该区域流派对是否出现多次 .box
es
$this.change(function () {
var area = $this.parents(".box").find(".area").val();
var genre = $this.parents(".box").find(".genre").val();
var numFound = 0;
$(".box").each(function () {
var cur_area = $(".area", this).val();
var cur_box = $(".genre", this).val();
if (area === cur_area && cur_box === genre) {
numFound += 1;
}
});
if (numFound > 1) {
alert("You already choose that " + (numFound - 1) + " times!");
}
});
您可以看到更新后的 fiddle here
关于javascript - 如果已经使用了两个选择框组合,如何使用 jQuery 进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319574/