user527892
user527892

Reputation:

Form validation - array loop?

I have the following code, which works nicely:

$('#register form .submit input').click(function(){    
    if(jQuery.trim($('#new-usr').val()) == '' || jQuery.trim($('#new-pwd').val()) == '' || jQuery.trim($('#new-pwd-confirm').val()) == ''){
      alert('Please fill in every required field (marked with an asterisk)');
      return false;
    }    
  });

However, I have a lot more fields to add to this and was thinking that there must be a way of storing the input ids in an array and looping through them, rather than adding a jquery.trim($('#inputid').val()) == '' for each one.

The jQuery validation plugin is a no-go in this instance for reasons that are too boring to go into here.

Upvotes: 0

Views: 350

Answers (3)

red-X
red-X

Reputation: 5128

give this a try:

$('#register form .submit input').click(function(){    
    var success = true;
    $("#register form .required").each(function(){
        if(this.value === ""){
            success = false;
        }
    });
    if(!success){
        alert('Please fill in every required field (marked with an asterisk)');
        return false;
    };
});

and give all your required fields the class required

EDIT this should do it than:

$('#register form .submit input').click(function(){    
    var success = true;
    $("#new-usr, #new-pwd, #new-pwd-confirm").each(function(){
        if(this.value === ""){
            success = false;
        }
    });
    if(!success){
        alert('Please fill in every required field (marked with an asterisk)');
        return false;
    };
});

Upvotes: 3

Alec Smart
Alec Smart

Reputation: 95900

You can use something like this:

http://jsfiddle.net/UDCWB/

Simply add a required class to your input variables and use jQuery to loop through them.

Upvotes: 1

oezi
oezi

Reputation: 51807

try something like this (using .each() to loop over selection - not really an array, but a lot easier to maintain):

$('#register form .submit input').click(function(){ 
  // add IDs here
  //     vvv  
  $('#new-usr, #new-pwd, #new-pwd-confirm').each(function(){
    if($(this).val()) == ''){
      alert('Please fill in every required field (marked with an asterisk)');
      return false;
    }
  }); 
});

Upvotes: 1

Related Questions