Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value exist in select box

Tags:

javascript

dom

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');

like image 775
Black Rider Avatar asked Oct 07 '10 06:10

Black Rider


2 Answers

with ecma6:

let option = document.getElementById('selbox').querySelector('[value="' + my_value + '"]');

this will find the first element that contains the attribute value="my_value".

PS: sorry by my spanglish :)

like image 121
min Avatar answered Oct 03 '22 18:10

min


You can't extend the methods the select-element has. So there will not be a solution without an extra function to check for the existence of a value in a select.

A "solution" without a loop could be the following...

function SelectHasValue(select, value) {
    obj = document.getElementById(select);

    if (obj !== null) {
        return (obj.innerHTML.indexOf('value="' + value + '"') > -1);
    } else {
        return false;
    }
}
like image 32
Andreas Avatar answered Oct 03 '22 19:10

Andreas