When designing my html form, I encountered an issue where I needed to display a message beneath blank fields when users did not fill them out. Initially, I used empty spans in the html code to hold potential error messages, which worked well. However, I decided to switch to generating these empty spans using javascript. Unfortunately, when attempting to set innerHTML for the empty spans, I received an error stating "Can not set property 'innerHTML' of undefined." The strange thing is that the variable statusMessageHTML is defined outside of both loops, so I am unsure why this error is occurring.
JS
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML;
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
}
// print a string in empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i].innerHTML = "Error Message"
}
return false;
});
HTML
<form method="POST" action="form.php">
<label>
<input type="text" name="name" placeholder="Your name*">
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
</label>
<label>
<input type="text" name="email" placeholder="Your e-mail*">
</label>
<label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</label>
<label>
<textarea name="message" rows="2" placeholder="Your message"></textarea>
</label>
<button type="submit" value="Submit">SUBMIT</button>
</form>
PD: My goal is to resolve this using solely javascript.