Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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";
    }  
});
share|improve this question
    
Does document.forms[1].getElementsByClassName("form-error-msg") really returns at least 4 elements? – acdcjunior Apr 15 at 14:55
    
Try splitting document.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:56
    
Also if there's only one form, you should use document.forms[0] to get it because arrays are zero-based in JavaScript. – Steve Francisco Apr 15 at 14:58
    
why not adding an id to the element you're trying to select by the following code document.forms[1].getElementsByClassName("form-error-msg")[3]; – Khalid Apr 15 at 14:58
    
getElementsByClassName return null or empty if nothing match with your request (fourth element with class name form-error-msg in your case) so you cant make null.css or empty.css; – Benjamin Poignant Apr 15 at 15:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.