tags:

views:

39

answers:

2

Hello all,

Is there any method other than running a for loop to check if a value exists in select box using js???? Im looking for something like document.getElementById('selbox').valueExists('myval');

A: 

you can do it with jquery

Use the Attribute Equals Selector

see in

http://stackoverflow.com/questions/2248976/check-if-value-is-in-select-list-with-jquery#answer-2248991

in javascript you can run like

 for (var i=0; i<document.getElementById('mySelect').options.length; i++)
           { 
            if (document.getElementById('mySelect').options[i].text == seachtext) 
            { 
             alert('found');
             break;
            } 
       }
Haim Evgi
Don't think the OP is looking for a jQuery solution...
chigley
Neither do I. Was playing with some kind of join and Option.prototype. Ran into more issues than I expected :)
mplungjan
I just reread the question, and while it is of course possible with pure JavaScript, I'd definitely use a jQuery approach as it's going to get messy otherwise!
chigley
A: 

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;
    }
}
john_doe
Will this be more efficient than using a loop????
Midhun Girish
No, it won't. Take a look at http://jsbin.com/ewevu3 and test it your self :)
john_doe
oops.. so i guess looping is all thts left... ill go with it...
Midhun Girish