jQuery: How to check if a value exists in an array?
Posted
by Jannis
on Stack Overflow
See other posts from Stack Overflow
or by Jannis
Published on 2010-05-21T00:15:00Z
Indexed on
2010/05/21
0:20 UTC
Read the original article
Hit count: 1562
Hello,
I am trying to write a simple input field validation plugin at the moment (more of a learning exercise really) and thought this would not be too hard, seeing as all I should have to do is:
- Get input fields
- Store them in array with each one's value
- On submit of form check if array contains any empty strings
But I seem to fail at writing something that checks for an empty string (read: input with no text inside) inside my array.
Here is the code I have so far:
var form = $(this), // passed in form element
inputs = form.find('input'), // all of this forms input fields
isValid = false; // initially set the form to not be valid
function validate() {
var fields = inputs.serializeArray(); // make an array out of input fields
// start -- this does not work
for (var n in fields) {
if (fields[n].value == "") {
isValid = false;
console.log('failed');
} else {
isValid = true;
console.log('passed');
};
}
// end -- this does not work
}; // close validate()
// TRIGGERS
inputs.live('keyup blur', function(event) {
validate();
});
Any help with how I can check if one of the fields is blank and if so return a isValid = false
would be much appreciated.
I also played around with the $.inArray("", fields)
but this would never return 0 or 1 even when the console.log
showed that the fields had no value.
Thanks for reading.
© Stack Overflow or respective owner