Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - selected option value contains string

I have an if statement where I'm trying to set a variable if the selected value of a select element does not contain "ALL"

Here's the code I've tried, but it always returns "%"...

if(!$("select.mySelect option:selected").filter(":contains('ALL')")) {
    selected_option = $("select.mySelect option:selected");
} else {
    selected_option = "%";
}

HTML

<select class="mySelect">
    <option value="ALLTYPE1">All type 1</option>
    <option value="CAR">Car</option>
    <option value="VAN">Van</option>
    <option value="ALLTYPE2">All type 2</option>
    <option value="PLANE">Plane</option>
    <option value="HELICOPTER">Helicopter</option>
</select>

Any ideas?

like image 904
Tom Avatar asked Aug 22 '26 18:08

Tom


1 Answers

Your if statement is incorrect. .filter() will never return a false value - it'll always be a jQuery collection - which can be empty, but never false. To test it there are any elements in the jQuery collection returned by .filter(), use the .length property.

Use:

if($("select.mySelect option:selected").filter(":contains('ALL')").length === 0) {
    ...

JSFiddle here: http://jsfiddle.net/egEX8/

like image 152
techfoobar Avatar answered Aug 25 '26 08:08

techfoobar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!