I'm relatively new to JavaScript, although I have recently turned a corner. I just wrote this code block to validate an email field that's generated by a CMS, but I'm getting a message that invalidEmailMsg is undefined. I have tried placing the variable declaration inside the function, outside the function, inside the if statement (basically flailing my arms around), but the message persists. Can anyone help? Please and thank you.
var email = document.getElementById("trouble-tickets-email");
email.addEventListener("keyup", function() {
var invalidEmailMsg = document.forms[1].getElementsByClassName("form-error-msg")[3];
var emailValue = email.value;
var emailPattern = /.+@.+\..+/;
if(emailPattern.test(emailValue) === false) {
invalidEmailMsg.css.style("display","block");
invalidEmailMsg.innerHTML = "custom message";
}
});
document.forms[1].getElementsByClassName("form-error-msg")
really returns at least 4 elements? – acdcjunior Apr 15 at 14:55document.forms[1].getElementsByClassName("form-error-msg")[3]
into separate variables and confirm each value before assuming the result was valid. – Steve Francisco Apr 15 at 14:56document.forms[0]
to get it because arrays are zero-based in JavaScript. – Steve Francisco Apr 15 at 14:58id
to the element you're trying to select by the following codedocument.forms[1].getElementsByClassName("form-error-msg")[3];
– Khalid Apr 15 at 14:58getElementsByClassName
return null or empty if nothing match with your request (fourth element with class name form-error-msg in your case) so you cant makenull.css
orempty.css
; – Benjamin Poignant Apr 15 at 15:00