I thought this was some interesting JavaScript that I used recently to detect if form fields were filled in. This was a case where if any of a particular group of fields were filled in, I needed to validate and make sure they were all passed in.

var allValues = $("input.someClass").map(function() { return this.value; }).get().join('');

if (allValues.length) {
  // do validation here to make sure all fields are filled in
  }

2 Comments

  1. Nathan Strutz says:

    Just a quick question – why not the serialize function – $(“form”).serialize(); – it returns a json string. I mean, your method is good too, just seems like it does a lot more than it needs.

  2. Ryan says:

    Interesting suggestion Nathan. I just played with .serialize() a little, and confirmed that you can give it a class. For my use, I need to know if a specific group of fields on the form was filled in. So I tried using this:

    var allValues = $("input.someClass").serialize();

    The problem is that it returns a string regardless if the fields are filled in or not. So I don’t see an easy way to use this to determine if the fields were filled in.

    Update: Ah, I just thought of a way this could be used. I could find out the length of a serialized empty form, then compare that, like:


    var emptyLength = 56; // determined when the form was built
    var allValues = $("input.someClass").serialize();
    if (allValues.length > emptyLength) {
    // then I know the fields were filled in
    }