I've gathered an Array (I think) of required form elements, and have added 'blur' listener.
var formInputs = $(':input').filter('[required]');
formInputs.each(function(i) {
$(this).on('blur', function() { // Each time we leave a 'required' field, check to see if we can activate the 'submit' button.
submitEnabler(formInputs);
});
});
So, once someone has left one of these fields, I want to run through this array using .every() and check if the fields are valid - that is if they have a 'success' class that I have defined.
function isValid(input) {
return input.hasClass('is_glowing_success');
}
function submitEnabler(inputs) {
console.log(inputs.every(isValid));
}
I keep getting back:
Uncaught TypeError: inputs.every is not a function
at submitEnabler
Now, I could do something like this...
for (var i = 0; i < inputs.length; i++) {
if ($(inputs[i]).hasClass('is_glowing_success')) {
console.log('yes');
} else {
console.log('no');
}
}
But, why can't I just use: Array.Prototype.every() ?
Because jQuery objects have no every
method, and formInputs
is a jQuery object.
If you want an array instead, call get()
to get one.
I've gathered an Array (I think) of required form elements...
No, it's just jQuery object. jQuery objects are very array-like, but they aren't arrays. Worse, they have some array-like methods (such as filter
and map
) that call their callbacks with different arguments than the equivalent Array.prototype
methods.
In isValid
, you'd need to handle the fact you're now dealing with a raw DOM element, which means either wrapping it with a jQuery object and using hasClass
:
function isValid(input) {
return $(input).hasClass('is_glowing_success');
}
or using the DOM's classList
:
function isValid(input) {
return input.classList.contains('is_glowing_success');
}
That latter works on all modern browsers, but not all older ones. However, it can be polyfilled on older browsers. More about that on MDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With