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
}
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.
28 October 2012, 1:44 amRyan 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:
28 October 2012, 9:34 amvar 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
}