根据除第一个选项选择外的所有选项更改CSS

时间:2018-09-27 16:56:40

标签: javascript jquery

尝试根据所选选项添加CSS类。第一个选项将始终在页面加载时被选择,标签不应显示。仅在选择其他选项时,标签应显示

$('#reason option').each(function() {
  if ($(this).is(':selected')) {
    $('.return-select label').addClass("form-select-dropdown");
  } else if ($('.return-select option:first').prop('selected', true)) {
    $('.return-select label').removeClass("form-select-dropdown");
  }
});
.form-select-dropdown {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-row return-select">
  <label class="show-default" for="reason">one</label>
  <select id="reason" name="reason" class="required">
    <option class="testing" value="">Default</option>
    <option value="Three">three</option>
    <option value="Four">Four</option>
    <option value="Five">Five</option>
  </select>
</div>

1 个答案:

答案 0 :(得分:1)

类似的事情应该可以完成:

$("#reason").change(function(event) {
    //get the selected option when the select changes its value
    var selected = $(this).find('option:selected');
    //if there is a value attribute on the selected option, then set the class
    if(selected.val()) {
        $('.return-select label').addClass("form-select-dropdown");
    } else {
        $('.return-select label').removeClass("form-select-dropdown");
    }
});

或像我们的朋友这样吼叫:

$("#reason").change(function(event) {   
    if(event.target.value) {
        $('.return-select label').addClass("form-select-dropdown");
    } else {
        $('.return-select label').removeClass("form-select-dropdown");
    }
});