I am looking to implement client-side validation using the Javascript Validation API.
Although I have created custom validation for certain fields, I now want to create a generic validation for all fields when they are left empty. In my attempt to do so with a for loop, I encountered an error when trying to access the variable [i] outside of the loop: Uncaught TypeError: Cannot read property 'value' of undefined
This is the code I have written thus far.
//Test
var test_field = document.querySelectorAll(".um-form-field");
var i;
for (i = 0; i < test_field.length; i++) {
test_field[i].addEventListener('keyup', test_function, false);
test_field[i].addEventListener('click', test_function, false);
test_field[i].addEventListener('invalid', test_function, false);
console.log(test_field[i].value);//this works every time i click or type a field!
function test_function (event) {
console.log(test_field[i].value);//This tells me an undefined variable every time I click on a field
}
}
EDITED 24/12: Appreciate the assistance from everyone. I have ended up using event.target as suggested in the comments.
This is my updated code (I'm still working out some issues with setCustomValidity):
var all_fields = document.querySelectorAll(".um-form-field");
var i;
for (i = 0; i < all_fields.length; i++) {
all_fields[i].addEventListener('keyup', field_function, false);
all_fields[i].addEventListener('click', field_function, false);
all_fields[i].addEventListener('invalid', field_function, false);
function field_function (event) {
if (event.target.value.length == 0) {
event.target.style.background = "#eb91ae";
event.target.setCustomValidity("error");
divError.style.display = "block";
divError.innerHTML = "You must complete this field";
event.target.parentElement.appendChild(divError);
} else {
event.target.style.background = "#9deb91";
event.target.setCustomValidity("");
divError.style.display = "none";
}
}
}