Homer_J
Homer_J

Reputation: 3323

jQuery dropdown if selected value

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.

Upvotes: 0

Views: 2054

Answers (2)

Dom
Dom

Reputation: 40459

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/

Upvotes: 0

Jason P
Jason P

Reputation: 27012

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

Upvotes: 3

Related Questions