Armitage2k Armitage2k - 1 month ago 6
CSS Question

JS - apply global function to all select boxes

I have 200+ select boxes, each individually named and with Yes / No / NA as answer options, and now would like to have the background of the option highlighted in red once it is selected.

This works fine via the onchange attribute when adding it to the specific select box, however since I have 200 of those, I do not want to apply this code one by one, but rather apply a global JS function to all boxes, which is where I am stuck. How can I address all select boxes with one JS function?

Javascript:

$('select').on('change', function () {
$(this).focus();
$(this).select();
$(this).className = this.options[this.selectedIndex].className;
});


CSS:

.green{ background-color:green; }
.red{ background-color:red; }


HTML:

<select id="boh_corridor" name="boh_corridor">
<option value=""></option>
<option value="Yes" class="green">Yes</option>
<option value="No" class="red">No</option>
</select>


EDIT: to be exact, the problem is that the option is not highlighted in either red or green at the moment, hence I am suspecting that the function is not being applied. The goal is to have the option highlighted in red/green when selected and while being selected from the dropdown menu.

Answer

jQuery objects don't have a className property; DOM elements do. Instead of

$(this).className = ...

use

this.className = ...

Example:

$('select').on('change', function() {
  $(this).focus();
  $(this).select();
  this.className = this.options[this.selectedIndex].className;
});
.green {
  background-color: green;
}
.red {
  background-color: red;
}
<select id="boh_corridor" name="boh_corridor">
  <option value=""></option>
  <option value="Yes" class="green">Yes</option>
  <option value="No" class="red">No</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Side note: You can use chaining with jQuery objects, rather than repeatedly calling $(): $(this).focus().select();

Comments