Liam
Liam

Reputation: 9855

Check multiple variables arent empty without IF statement jQuery

Im trying to build a client side validation on my form and I'm wondering if theres a better way to do it than I imagined?

If a field is empty, then I want the parent container border to turn red, I could d this with a list of if statements...

// Complete Signup Validation
$("#signup-com-btn").click(function() {

    var a = $("input.first_name").val();
    var b = $("input.surname").val();
    var c = $("input.email_addr").val();
    var d = $("input.user_age").val();
    var e = $("select.user_type").val();
    var f = $(".profile_image").val();

    if(a==''){
        $(this).parent().css...
        return false;
    }
    if(b==''){
        $(this).parent().css...
        return false;
    }       

...and so on...

});

Upvotes: 0

Views: 994

Answers (5)

Michiel Cornille
Michiel Cornille

Reputation: 2097

since you're using jquery, jquery validation is a nice option that covers most of your form validation needs!

http://plugins.jquery.com/validation/

Upvotes: 0

David Thomas
David Thomas

Reputation: 253416

I'd suggest:

$('input, select, .profile_image').filter(function(){
    return !$(this).val().length;
}).parent().css('border-color', '#f00');

Though I'd prefer to use classes, in order to identify the relevant items and to style the parent element, rather than manually modifying CSS rules, to give:

$('.inputClassName').filter(function(){
    return !$(this).val().length;
}).parent().addClass('redBorder');

Upvotes: 1

PSR
PSR

Reputation: 40338

apply same class to all

var valid = true;
$('.className').each(function(){
  if($(this).val() == ""){
   $(this).parent()....  
     valid = false;
  }  
});
 return valid ;

Write this in click function

Upvotes: 1

jterry
jterry

Reputation: 6269

You could do them all in one loop, if it really is all of them:

$('#signup-com-btn').click(function() {
    var valid = true; // optimist

    $('input, select, .profile_image').each(function() {
        if($(this).val() == '') {
            valid = false;
            $(this).css('border', '1px solid red');
        }
    }

    if(!valid)
        return false;
}

Upvotes: 1

Perocat
Perocat

Reputation: 1521

You can create an array and simulate a foreach loop. Here a Javascript example:

function check_empty(){
    var a = document.getElementById('a')
    var b = document.getElementById('b')
    var c = document.getElementById('c')

    var abc = new Array(a, b, c);

    for(i=0; i<abc.length; i++){
        //do your if stuff here...
    }

Upvotes: 0

Related Questions