views:

41

answers:

4

For example, I'm using the script below to check for empty fields :

$('a.submit').click(function() {
 if ($('.LoginData').val() == "")  {
  $('input:text[value=""]').attr('style', 'border-color:#FF0000;');
 } else {
  $(this).parents('form').submit();
 }
});

All the input elements have the class LoginData, so I used the jQuery class selector which selects all the elements containing that class. However, when the if condition finds a field that isn't blank, it just stops there.

I think its a normal behavior for if statements, are there any alternative to this?

Thanks.

+3  A: 

".val()" only has one return value -- it can only give you the value of one element; That one will be the first element on the $() collection.

$('a.submit').click(function() 
{
  var ok = true;
   $('.LoginData').each(function() 
   {  
       if($(this).val() == "")  
       { 
              $(this).attr('style', 'border-color:#FF0000;'); 
              ok = false;
       }
   }
   if (ok)
   {
      $(this).parents('form').submit(); 
   } 
});
James Curran
A: 

Your code is currently only looking at the first element. You'll need to use .each() in conjunction with your check to make sure that it's going as planned.

Also your loop in it's current state will immediately submit the form if the field is not empty.

Angelo R.
A: 

val() only returns the value of the first matched element, so you can't use this to verify if the form is filled out.

You need to use the jQuery.each() method to iterator over the '.loginData' items.

A good solution would be to use the each method, attach a class to the elements that are empty (something like validate-empty). This can be used to attach a style to an element that shows the user that it is required (just like you are doing above, but with a defined class). Then you can check the form, something like $('#my-form .validate-empty').size() == 0 to see if there are errors before submitting.

partkyle
A: 

you need to use each()

Moin Zaman