HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Checking for a value on selectors

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkingforvalueselectors

Problem

I've got some pretty simple validation that I'm working on, but it seems like I'm repeating myself a bunch of times. There has to be a better way of doing this. I'm simply checking if there is a value filled in for specific fields and apply a color if the value isn't filled in. There are also other areas where the validation is different where I'm checking a valid phone number. So I couldn't simply apply this to all inputs. Here's some of my code:

var x = $();
var pass = true;

function validateForm(){
        x = $('input#zip').val();
        if (x == null || x == "") {
            $('#ziplabel').css('color','#fff');
            pass = false;
        } else {
            $('#ziplabel').css('color','#444');
        }
        x = $('input#fname').val();
        if (x == null || x == "") {
            $('#fnamelabel').css('color','#fff');
            pass = false;
        } else {
            $('#fnamelabel').css('color','#444');
        }
        x = $('input#lname').val();
        if (x == null || x == "") {
            $('#lnamelabel').css('color','#fff');
            pass = false;
        } else {
            $('#lnamelabel').css('color','#444');
        }

}

Solution

Yup, you can iterate the input fields. For this sort of thing you should also be using classes, instead of inline CSS. Using jQuery .each and .togggleClass you can create something like this:

function validate () {

  $('#form input').each(function () {
     var $el = $(this)
     $el.prev('label').toggleClass('invalid', $el.val()); 
  });

}


And your stylesheet has a rule like this;

label {
  color: #444;
}

label.invalid {
  color: #fff;
}


If you want to check if the form was valid then you can check for the existence of a field with that class. $('#form input.invalid').length. Or you can set a boolean in the each function if you want to separate the logic from the HTML.

Code Snippets

function validate () {

  $('#form input').each(function () {
     var $el = $(this)
     $el.prev('label').toggleClass('invalid', $el.val()); 
  });

}
label {
  color: #444;
}

label.invalid {
  color: #fff;
}

Context

StackExchange Code Review Q#41112, answer score: 5

Revisions (0)

No revisions yet.