Kiran Lala
Kiran Lala

Reputation: 146

Change css based on all options except first option select

Trying to add CSS class based on the option selected. The first option will always be selected on page load, the label should not show. Only on the selection of other options, the label should show

$('#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>

Upvotes: 0

Views: 385

Answers (1)

Wolgan Ens
Wolgan Ens

Reputation: 385

Something like this should do the job:

$("#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");
    }
});

or like our friend said bellow:

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

Upvotes: 1

Related Questions