比较来自两个选择的选项,如果值 != id 则隐藏

Compare options from two selects and hide if value != id

我有两个 select 元素。我想比较第一个 select 中 selected 选项的值与第二个 selected 选项的 id 的值。我的 jQuery 代码如下所示:

$("#billing_zone").change(function(){
  if ($('.zone:selected').val() != $('.day').attr("id")) {
    $(".day").hide();
  } else {
    $(".day").show();
  }
});
<select name="billing_zone" id="billing_zone" class="select " data-placeholder="">
   <option class="zone" value="10">Birkeland, Tveit, Høvåg</option>
   <option class="zone" value="6">Lillesand Birkeland bedrift</option>
   <option class="zone" value="13">Lillesand</option>
</select>
<select name="billing_delivery_day" id="billing_delivery_day" class="select " data-placeholder="">
   <option class="day" id="10" value="1">Mandag</option>
   <option class="day" id="10" value="2">Tirsdag</option>
   <option class="day" id="6" value="3">Onsdag</option>
   <option class="day" id="13" value="3">Onsdag</option>
</select>

然而,这总是隐藏所有的选项。我做错了什么?

您可以只使用 id 选择器,例如:

$(".day[id="+selected_zone+"]")

因此隐藏所有选项的更改并仅显示与所选区域值相关 id 的选项:

$("#billing_zone").change(function(){
    var selected_zone = $('.zone:selected').val();

    $(".day").hide(); //Hide all the options
    $(".day[id="+selected_zone+"]").show(); //Show the spedific one that match the selected
});

注意: id 属性在同一文档中应该是唯一的,因此最好使用 common classesdata-* attributes 代替。

希望对您有所帮助。

$("#billing_zone").change(function(){
    var selected_zone = $('.zone:selected').val();
    
    $(".day").removeAttr('selected').hide();
    $(".day[id="+selected_zone+"]").show().eq(0).attr('selected', 'selected');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="billing_zone" id="billing_zone" class="select " data-placeholder="">
 <option class="zone" value="10">Birkeland, Tveit, Høvåg</option>
 <option class="zone" value="6">Lillesand Birkeland bedrift</option>
 <option class="zone" value="13">Lillesand</option>
</select>
<select name="billing_delivery_day" id="billing_delivery_day" class="select " data-placeholder="">
 <option class="day" id="10" value="1">Mandag</option>
 <option class="day" id="10" value="2">Tirsdag</option>
 <option class="day" id="6" value="3">Onsdag</option><option class="day" id="13" value="3">Onsdag</option>
</select>