Sackadelic
Sackadelic

Reputation: 1019

How to check if a value exists in a select box using vanilla JS?

I want to create a function that accepts an argument of check that will loop through select box options and values and check to see if the value exists or not. I have it working (kinda) but it only checks the first option. If you run checkOption('red), you get an alert that Option Exists. However, if you run checkOption('green'), nothing happens.

I'm doing something simple here, but I can't figure it out. Thanks for any and all help.

Working CodePen:

CodePen

JavaScript:

let selectBox = document.querySelector("select");
let options = selectBox.querySelectorAll("option");

function checkOption(check) {
    options.forEach((o) => {
        if (o.value === check) {
            return true; // returns undefined either way.
        }
    });
}
}

Edit: I am now able to get console.log() to print to the console, but I'm trying to return either True or False. How would I amend the above function to return True or False? So far, this only returns undefined.

Upvotes: 0

Views: 855

Answers (2)

JakeParis
JakeParis

Reputation: 11210

You need to loop through the options in your function. You can also shorten by using forEach on the collection:

function checkOption(check) {
    options.forEach( o => {
        if( o.value === check) {
            alert(`${check} is available`);
        }
    });
}

You could condense even more by using the array filter() function as well. You just need to make treat the options NodeList as an array but sticking it through the Array.from() method first:

function checkOption(check) {
   if( Array.from(options).filter( o => o.value === check ).length )
      alert(`${check} is available`);
}

or even shorter, let the function returns true or false to indicate the presence of the given option value.

function checkOption(check) {
   return Array.from(options).filter( o => o.value === check ).length > 0;
}

Upvotes: 2

Wais Kamal
Wais Kamal

Reputation: 6180

You should use options.length in your loop. Besides that, it is good practice to define variables before using them. Your return statement should also be called immediately after a match is found to avoid unnecessary iterations, so you better include it in your if statement.

let selectBox = document.querySelector("select");
let options = selectBox.querySelectorAll("option");

function checkOption(check) {
  for (var i = 0; i < options.length; ++i) {
    if (selectBox.options[i].value === check) {
      alert(`${check} is available`);
      return;
    }
  }
}

Upvotes: 0

Related Questions