2

I'm trying to add a class to select option value based on array values received from ajax call.

HTML

<select id="my_id">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

JAVASCRIPT

//array received from ajax call 
var array = [1,3,5]

// loop through dropdown options 
$("#my_id > option").each(function(i) {

    // if option value in array, add class 
    if ( array.indexOf(i.value) != -1 ) {

        // set matching values to red color 
        $(this).addClass("red");
    }

});
1
  • Just a typo. I do have different values in there so I just quickly typed this small sample. Good eye! Commented Sep 10, 2019 at 1:35

1 Answer 1

2

The first argument to the callback is the index being iterated over, not the element. To get to element, reference this, so that this.value gets you to the value you want to examine.

But the .value of an element will always be a string, so turn the array of numbers into an array of strings as well.

You can also consider using .includes instead of an indexOf check, it's more appropriate when just checking to see if an array includes a value (and is a bit more readable):

//array received from ajax call 
var array = [1, 3, 5]
const arrayStrs = array.map(String);

// loop through dropdown options 
$("#my_id > option").each(function() {
  // if option value in array, add class 
  if (arrayStrs.includes(this.value)) {

    // set matching values to red color 
    $(this).addClass("red");
  }

});
.red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="my_id">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>

(you could also use a Set instead of an array, it would lookup in O(1), and may well be more appropriate because you don't need an ordered collection, just a collection - but that doesn't matter much)

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Thank you for you time and your help! Your help is much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.