Search code examples
jquerycomparisonecmascript-5

Can I use jQuery .each() in a comparison?


Quick question: Can I use jQuery .each() in a comparison?

For example if I have a form with multiple fields with an ID starting my "input":

if ($('[id^=input]').each().val() == '') {
// some functions here
}

(I want to make sure all fields are empty)

Thanks!


Solution

  • No, that's not going to work. each() doesn't work like that. Plain old Javascript however has an every() function that works on arrays. So you could do something like this instead:

    if ($('[id^=input]').toArray().every(function(item){return item.value === ""})) {
           // Do stuff
         }
    

    If you don't have to worry about older browsers you can make it a little easier on the eyes with:

    if ($('[id^=input]').toArray().every(item => item.value === "")){ 
        //do stuff
        }