0

I have the following code:

$('[name^=business_] option:selected').each(function(){
    var bus = $(this).text();
    alert(bus);
});

This brings back the selected values of all the dropdowns with the name beginning with business_ - this is fine.

What I need is, if none of the dropdowns have a selected value equal to or higher than 1 then return an alert.

But I cannot fathom how to achieve this, I've tried looking at adding the values together but no joy - any pointers welcome.

2 Answers 2

3

Iterate over the dropdowns, and once you find one with a value greater than one, set a flag and break the loop.

var foundOne = false;
$('[name^=business_] option:selected').each(function() {
    if ($(this).val() >= 1) {
        foundOne = true;
        return false;
    }
});

if (!foundOne) {
    alert('No selected options had a value of 1 or higher'); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply but not quite there - what I need is if all 10 dropdowns are not equal to or greater than 1 then an alert needs to happen - not at each iteration. Does that make sense?
I think you may be confused on the return false;. That is returning from the anonymous function within each(). It doesn't return from whatever validation function this is all contained in. You can return false; from each() to break the loop and stop iterating.
THANK YOU for the update - a stonking piece of code that works perfectly. That has had me stumped for hours!!!
0

Why not use .filter() then check the length:

   var arr = $('select option:selected').filter(function(){
       if(this.value > 1)
           return this; 
    });

    if(arr.length) // arr.length > 0 also valid
        alert('yes');

DEMO: http://jsfiddle.net/vaTVX/1/

1 Comment

Because we only need one item to meet the criteria. filter() will iterate the entire list even when the first item meets the success condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.