2014-09-30 98 views
0

我有三个选择选项下拉菜单,类为'电影',但这些值是链接的,所以我必须全部选择以获得结果。在我的情况下,HTML代码如下所示:Jquery自动选择相同类别的选择选项

<select name="sc30" id="sc30" onchange="autoSelect()" class="film"> 
    <option>Choose an option...</option> 
    <option>---</option> 
    <option>White</option> 
    <option>Black</option> 
</select> 

<select name="ij10" id="ij10" onchange="autoSelect()" class="film"> 
    <option>Choose an option...</option> 
    <option>---</option> 
    <option>Red</option> 
    <option>Green</option> 
    <option>Gold</option> 
</select> 

<select name="sc100" id="sc100" onchange="autoSelect()" class="film"> 
    <option>Choose an option...</option> 
    <option>---</option> 
    <option>Gold glossy</option> 
    <option>Silver glossy</option> 
</select> 

如果我选择ID =“SC30”选择其他两个选择选项必须走价值“---”。或者,如果我从ID =“SC100”选择选项黄金光泽从这个类“膜”其他选项一定要把这个值---

我认为我必须使用jQuery的每() 方法。但是如何检查是否选择了选项,并且在没有选择选项的情况下使用“---”值从该类别中选择其他选项。下面的代码无法正常工作。

function autoSelect() { 
    $('.dummy').each(function(index, value){ 
     if($(this).val() != '---') { 
      $(".dummy").val($(".dummy option:eq(1)").val()); 
     } 
    }); 
} 

回答

0

$(function() { 
 
    $('select.film').on('change', function() { 
 
    var cb = $(this); 
 
    if (2 === cb.prop('selectedIndex')) { 
 
     $('select.film').not(cb).prop('selectedIndex', 1); 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select name="sc30" id="sc30" class="film"> 
 
    <option>Choose an option...</option> 
 
    <option>---</option> 
 
    <option>White</option> 
 
    <option>Black</option> 
 
</select> 
 

 
<select name="ij10" id="ij10" class="film"> 
 
    <option>Choose an option...</option> 
 
    <option>---</option> 
 
    <option>Red</option> 
 
    <option>Green</option> 
 
    <option>Gold</option> 
 
</select> 
 

 
<select name="sc100" id="sc100" class="film"> 
 
    <option>Choose an option...</option> 
 
    <option>---</option> 
 
    <option>Gold glossy</option> 
 
    <option>Silver glossy</option> 
 
</select>

0

尝试这种情况:从所有选择框除去onchange="autoSelect()"和如下所示结合change事件,并选择第二option为每个选择框除了当前为其change事件烧制 -

$(function(){ 
$('.film').change(function(){ 
    //iterate all other select box except current using `not(this)` 
    $('.film').not(this).each(function(){ 
     // get selected option for the current select box 
     var $selected = $(this).find('option:selected'); 
     // if index of selected option is greater than 1, 
     // it means option is selected. 
     if($selected.index()>1)  
      $(this).val($(this).find('option:eq(1)').val()); 
    }); 
}); 
}); 

DEMO

0

我只是删除这两行代码:

var $selected = $(this).find('option:selected'); 
if($selected.index()>1) 

,并已就行了!

$(function(){ 
$('.film').change(function(){ 
    //iterate all other select box except current using `not(this)` 
    $('.film').not(this).each(function(){ 
     $(this).val($(this).find('option:eq(1)').val()); 
    }); 
}); 
});