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

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

Error message: Unexpected character found at the beginning of JSON data - REST API using node.js and Express

Recently, I have embarked on the journey of learning REST API with node and express. My main goal is to achieve file read and write operations using APIs. However, a frustrating error arises when attempting to hit the API through Postman. Strangely enough, ...

Creating a Stylish Funnel Graph using CSS

I am currently working on customizing a funnel chart based on data from my database that is displayed on the page. Everything is functioning correctly except for the CSS rendering of the chart. <ul id="funnel-cht"> <li style="height:70px;widt ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...

What is the best way to utilize the forEach method in React to manipulate a navigation element containing multiple links?

Here is the code I'm trying to convert: document.addEventListener("scroll", function() { const links = document.querySelectorAll(".nav-link"); for (const l of links) l.classList.toggle('scrolling', window.scrollY &g ...

Gather information from a customizable Bootstrap table and store it in an array

Currently, I have a bootstrap table configured with react-bootstrap-table-next, enabling users to edit cells and input their desired values. After completing the editing process, individuals can click on the "Submit" button to save the table values, which ...

Operating on Javascript Objects with Randomized Keys

Once I retrieve my data from firebase, the result is an object containing multiple child objects. myObj = { "J251525" : { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c3823212 ...

Using jQuery to redirect a page based on the IP address of the visitor

I am looking to implement Jquery code on the index page of www.propertyhere.com The aim is to redirect visitors based on their geographical IP location to specific pages: if the user's IP is from AU: http://www.propertyhere.com/Country/AU/search-t ...

Navigate back to the previous page upon form submission to a PHP file, with a div dynamically populated with targeted content

I'm facing a logic dilemma: I have a webpage with a div called #content, where I've embedded another page containing a form for submitting data* (there are other pages loaded into #content as well, but they are not active at the same time, one o ...

JavaScript functions cannot be applied to input fields in jQuery

I am having trouble saving values into a database where I need to calculate the total and grand total. I want to do the calculation in the input field, but my attempts have not been successful. It seems like the issue lies with $('.multTotal',thi ...

No response from jQuery's $.getJSON() function

I'm currently experimenting with jQuery by using a script that I wrote. As a beginner in learning jQuery, I am trying to read data from a .json file and display it in a div. function jQuerytest() { $.getJSON( "books/testbook/pageIndex.json", func ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Modify the base URL with JavaScript

Is it possible to dynamically change the href using JavaScript? I attempted to make this change with the code below in my HTML file, but unfortunately, it didn't work: <base href="/" /> <script type="text/javascript"> function setbasehr ...

Transform the look of an inactive hyperlink

Can the visual style of an HTML link be modified when it is disabled? For instance, by implementing something like this: a.disabled { color:#050; } <a class="disabled" disabled="disabled" href="#">Testing</a> The code snippet above appears ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...

What is the correct way to utilize preloads and window.api calls in Electron?

I am struggling with implementing a render.js file to handle "api" calls from the JavaScript of the rendered HTML page. The new BrowserWindow function in main.js includes: webPreferences: { nodeIntegration: false, // default value after Electr ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer: angular.module('LBTable').service('exportTable', function () { function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) { //If JSONData isn't an object, parse the ...