Unfortunately I don't have access to JQuery and all it's nicety. But I do have access to JavaScript. How do I check if an OPTION exist in a HTML Select?
EDIT: To clarify, I need to know if an option exist. So for example:
<select>
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
I check if "Hyndai" is an OPTION, and it is not.
Use the value property on the HTMLOptionElement object to check if there is an option with the specified value attribute. Note that an option's value will fall back to its text content if no such attribute is provided.
$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
document.getElementById("myselect").options[0] //accesses first option via options[]
would select the first option in your select. If it fails you know that there are no options in your select. If you get data by appending .value
after the .options[0]
it's not empty. Without javascript you will not be able to achieve this. Only HTML does not deliver the functionality you want.
for (i = 0; i < document.getElementById("myselect").length; ++i){
if (document.getElementById("myselect").options[i].value == "Hyndai"){
alert("Hyndai is available");
}
}
I ran into this issue today and used these answers to come up with my own, which I think is a little easier to use.
I loop through the select
's options (caching the length), but I put that loop into the HTMLSelectElement itself through it's prototype, as a .contains()
function.
HTMLSelectElement.prototype.contains = function( value ) {
for ( var i = 0, l = this.options.length; i < l; i++ ) {
if ( this.options[i].value == value ) {
return true;
}
}
return false;
}
Then to use it, I simply write this:
if ( select.contains( value ) ) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With