How to check if a value exist in select box

Viewed 34339

Is there any method other than running a for loop to check if a value exists in select box using JavaScript?

I am looking for something like document.getElementById('selbox').valueExists('myval');

6 Answers

Based on @Haim Evgi:
You can transform select.options to an array and can filter like this:
Array.from(nSelect.options).filter(nOption => /*true or false)*/ When the Array still contains options after filtering a match has happend so the length must be > 0.

Below a snippet using this by searching after value or text of the options.
First checkbox for searching after value, second after innerText searching.

function selectContainsOption(nSelect, nValue, nCheckValue, nCheckText){ // HTMLElement, ~String, ~boolean, ~boolean
    nValue = (nValue == null ? "" : nValue);
    nCheckValue = (nCheckValue == null ? true  : nCheckValue);
    nCheckText = (nCheckText  == null ? false : nCheckText);
    // get options as array, filter the array and check if there is any option left
    return (
        Array.from(nSelect.options).filter(
            nOption => (nCheckValue && nOption.value == nValue) || (nCheckText && nOption.innerText == nValue)
        ).length > 0
    );
}
<select>
    <option value="1">Zahl 1</option>
    <option value="2">Zahl 2</option>
    <option value="3">Zahl 3</option>
    <option value="4">Zahl 4</option>
    <option value="5">Zahl 5</option>
    <option value="6">Zahl 6</option>
    <option value="7">Zahl 7</option>
    <option value="8">Zahl 8</option>
    <option value="9">Zahl 9</option>
    <option value="a">Zeichen a</option>
    <option value="b">Zeichen b</option>
    <option value="c">Zeichen c</option>
    <option value="d">Zeichen d</option>
    <option value="e">Zeichen e</option>
    <option value="f">Zeichen f</option>
</select>
<b> search: </b>
<input type="text" value="0" onchange="this.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerText = selectContainsOption(this.previousElementSibling.previousElementSibling, this.value, this.nextElementSibling.checked, this.nextElementSibling.nextElementSibling.checked);"/>
<input type="checkbox" checked="checked" onchange="this.previousElementSibling.onchange()"/>
<input type="checkbox" checked="checked" onchange="this.previousElementSibling.previousElementSibling.onchange()"/>
<b> contains: </b>
<span>false</span>

Related