user1469742
user1469742

Reputation:

jQuery - Shorthand for multiple identical IF conditions and simultaneously matched for several elements?

Is there a shorter way of writing this for jQuery? Bundling it somehow? Seems awfully inefficient.

if (
   ($('#fname-field').val() == '')  || 
   ($('#lname-field').val() == '')  || 
   ($('#cell-field').val() == '')   || 
   ($('#email-field').val() == '')  || 
   ($('#street-field').val() == '') || 
   ($('#pcode-field').val() == '')  || 
   ($('#city-field').val() == '')   || 
) { // Do something }

I have searched around but haven't found an answer yet. I don't think the following is equivalent:

if ($('#fname-field, #lname-field, #cell-field etc...' == '')) { // Do something }

It's not equivalent since it doesn't run the conditions as a group, instead individually? Right?

Upvotes: 2

Views: 599

Answers (4)

Horen
Horen

Reputation: 11382

You could give all the elements that you want to validate a class and then use jQuery's each function

$('.validate').each(function(index) {
  if ($(this).val() == '')
     alert("empty");
});

http://api.jquery.com/each/

Or if you just want an alert once do:

$('.validate').each(function(index) {
  if ($(this).val() == ''){
     alert("empty");
     return false;
  }
});

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55750

You can try this approach

var isCheck = false;
 var elems = $('#fname-field ,#lname-field , #cell-field , #email-field ,#street-field ,#pcode-field , #city-field' );
        $.each(elems , function() {
            if($this).val() == ''){
               isCheck = true;
               return false
            }
        });

        if(isCheck){
           // Your code here
        }
        else{
          //  Do something else
        }

Upvotes: 0

TimTastic
TimTastic

Reputation: 383

var i  = 0; 
$('input').each(function() { 
if($(this).val().length == '0') { 
i++;; 
}  
});
alert("Found " + i + " empty fields");

http://jsfiddle.net/QrkWz/2/

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You can do this..

if ($('#fname-field, #lname-field, #cell-field/*, ..*/')
    .filter(function () { 
         return $(this).val(); 
     }).length)

Upvotes: 0

Related Questions