0

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.

3 Answers 3

3

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;
    };
});
Sign up to request clarification or add additional context in comments.

2 Comments

I can't get at the html to add the class, I'm afraid, hence the inability to use the validation plugin, thanks though.
@ScottBrown in that case you should replace the #register form .required with a selector that can select all required fields another way, something like #new-usr, #new-pwd, #new-pwd-confirm
1

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

3 Comments

I always forget about .each(), thanks. The validation works great but for some reason it's not returning false. Any ideas why?
because the return false is for the each function and not for the submit function
@red-X: thanks for the hint, i missed that -your solution is clearly the better one.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.