Error: Unable to assign value to the innerHTML property of an undefined element created by JavaScript

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>

CODEPEN

PD: My goal is to resolve this using solely javascript.

Answer №1

In the statusMessageHTML object, there is no attribute [i] and that's why the message is showing as undefined. Trying to set the innerHTML attribute of a non-existent element will result in an error.

var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');

myForm.addEventListener('submit', function(){
  event.preventDefault(); 
    var statusMessageHTML;     
    var elementArray = [];
    // create empty spans
    for(i = 0; i < formFields.length; i++){
      statusMessageHTML = document.createElement('span');
        statusMessageHTML.className = 'status-field-message';
      formFields[i].appendChild(statusMessageHTML);     
      elementArray.push(statusMessageHTML);
    }
    // print a string in empty spans
    for(i = 0; i < elementArray.length; i++){
      elementArray[i].innerHTML = "Error Message"
    }      
  return false;
});
<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>

Answer №2

statusMessageHTML is being treated as an element object in the first for loop, but in the second loop it is assumed to be an array.

    // create empty spans
for(i = 0; i < formFields.length; i++){
  statusMessageHTML = document.createElement('span');
  statusMessageHTML.className = 'status-field-message';
  formFields[i].appendChild(statusMessageHTML);  
  statusMessageHTML.innerHTML = "Error Message"
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with electron-vue: Unable to modify Vuex state when using RxJS subscribe

I need help with my code involving two functions in the mutations and two pieces of state const state = { files: [], uploadProgress: 0 } const mutations = { SET_UPLOAD_IMAGE: (state, files) => { state.files = files }, UPLOAD_IMAGE: ( ...

What is the process for enabling the experimental-modules option when running an npm package's bin command?

Beginning with Node v8.5.0, the support for ES6 style modules has been introduced. import x from 'x' You can access this feature by running node using the --experimental-modules option, like so: node --experimental-modules test.mjs By utilizi ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

WebAPI provides a similar functionality to an array in JavaScript through the use of IQueryable

I have a WebAPI method that returns an IQueryable of a 'complex' object in the following format: [Route("api/INV_API/deptSelect")] public IQueryable<DEPTNAME_DESCR> GetDistinctDeptSelect([FromUri] string q) { if (q != null) ...

Can a PHP file be used in the src attribute of an HTML5 audio element?

Within my PHP code, I am attempting to include an audio tag like this: '<audio src="song.php" />'.$fallback.'</audio>' I have experimented with various approaches in the "song.php" file, but unfortunately, none of them hav ...

Troubleshooting: Issues with JQuery validation for cross-domain URLs

I'm fairly new to using JQuery and I have a specific requirement which involves validating a link from another domain. If the validation is successful, I need to redirect (open the page in a new window) to that link. Otherwise, I should display an ale ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

What is causing elements like divs, paragraphs, or text not to display within an ion-item after an ion-input is added?

I am currently working on validating a simple form and everything seems to be functioning properly. However, I have encountered an issue with displaying text messages within an ionic 3 list item. The ion-item consists of an ion-input element. When I place ...

How can we transition a line of code from PHP to Smarty?

I'm currently working on converting a php line of code to Smarty. I've managed to convert the variable successfully, but I am struggling with incorporating the small syntax before it. Below are both sets of syntax - how can I include link_it with ...

Tips for aligning 2 divs in the same position?

I am working on a slider feature that includes both videos and pictures. I need to ensure that the videos are hidden when the device width exceeds 600px. Here is the HTML code snippet: <video class="player__video" width="506" height="506" muted preloa ...

Using HTML5 datetime-local to only accept dates in the format Y-m-d

I am currently working on a form that includes a datetime-local input field. <input type="datetime-local" id="datetime" /> After clicking on the today button, the date is automatically set to today's date like this: 2018-11-05 --:-- However ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Verify in JavaScript if the script is executing within a WinStore (WinJS) program

I am in the process of developing a JavaScript library that is compatible with both Windows Store (WinJS) applications and traditional HTML/JavaScript apps. The dependency I am utilizing loads dynamically and has separate SDKs for WinJS apps and standard w ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...

Instructions for implementing personalized horizontal and vertical scrolling within Angular 9

I am currently working on an angular application where users can upload files, and I display the contents of the file on the user interface. These files may be quite long, so I would need vertical scrolling to navigate through them easily. Additionally, fo ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

Why isn't the selected option appearing first?

I have written a PHP code to display the specified div <div id="main_catsel"> <select id="maincat" > <option value="1">none</option> <option value="2">Computer</option> <option value="4">Refrigerator& ...