Issues with addEventListener causing object element to return undefined

Currently, I am in the process of creating a basic form where users are required to input their project name, their name, and some additional information.

Since each type of project has its own unique page layout, I have decided to create a module containing the necessary getElementById and addEventListener functions, to prevent repetitive code in each page. The code snippet below showcases how this module is implemented on one of the pages:

// (imports)...

let project = {
  author: null,
  name: null,
  mission: {
    file: null,
    path: null,
  },
  sd: {
    code: null,
    path: null,
  },
  modloaderfolder: null,
};

window.addEventListener("DOMContentLoaded", () => {
  project.mission = handleMission();
  project.sd = handleSD();
  project.modloaderfolder = handleModloader();
  project.name = handleName();
  project.author = handleAuthor();
// ...

However, I am encountering an issue where the elements of objects are returning as undefined in the following two functions:

export function handleName() {
  const project = {};
  const txt_name = document.getElementById("name");
  txt_name.addEventListener("change", () => {
    project.name = txt_name.value;
  });
  return project.name;
}

export function handleAuthor() {
  const project = {};
  const txt_author = document.getElementById("author");
  txt_author.addEventListener("change", () => {
    project.author = txt_author.value;
  });

  return project.author;

}

// Returns undefined

Interestingly, some other functions are working properly without any issues, and I am unable to pinpoint the cause. These are the functioning functions:

export function handleSD() {
  const project = { sd: {} };
  const input_sd = document.getElementById("sd");
  input_sd.addEventListener("change", () => {
    document.getElementById("sel-sd").innerHTML = "";
    Array.from(input_sd.files).forEach((file) => {
      document
        .getElementById("sel-sd")
        .insertAdjacentHTML("beforeend", `<option>${file.name}</option>`);
    });
    if (!input_sd.files[0]) return;
    const path = input_sd.files[0].path;
    project.sd.path = path.substring(0, path.lastIndexOf("\\")) + "\\";
    project.sd.code = project.sd.path.substring(
      project.sd.path.lastIndexOf("\\"") - 5,
      project.sd.path.length - 1
    );
  });

  return project.sd;
}

// This function correctly returns "sd: { path: ..., code: ...}"

Upon observation, I noticed that when returning an object, it updates properly with each change, but when returning an object's element, it consistently returns as undefined.

Answer №1

In a scenario where the key is empty and unable to be changed due to the nature of copying a primitive value is done by value. However, when dealing with an object that contains the key as a string, once the onchange function is triggered, the value of the key within the object is altered, causing automatic changes in the object itself due to the copy being done by Reference. For additional information on this topic, refer to this resource

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

Caution: It is essential for each child within a list to possess a distinct "key" property - React Native issue alert

Hello everyone, I am currently working on building a list in an app using react-native. I have been following a tutorial video and my code is identical to the instructor's, but I keep encountering an error that says each child in the list needs a key ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

What is the best way to set up the correct pathway for displaying the image?

I'm currently facing a challenge with displaying an image from my repository. The component's framework is stored in one library, while I'm attempting to render it in a separate repository. However, I am struggling to determine the correct p ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

Identifying when a page-loading or reloading event has been canceled

When the Cancel button is pressed during page load/reload, the content of the page loads partially. Is there a more effective way to address this issue rather than displaying incomplete content? For instance, consider showing a message such as "Page load ...

Encountering an issue while attempting to utilize the .find() method in Mongoose

Currently, I am in the process of setting up a database using MongoDB and integrating the Mongoose ODM with Node.js. After running the code multiple times without any issues, I encountered an unexpected error when adding the last block to utilize the .find ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Incorporate Vuetify's v-stepper seamlessly with Vue router for dynamic functionality

Seeking assistance in integrating vuetify's v-stepper with vue router. Specific requirements include: Assigning each step its own route (e.g. /myform/step1, /myform/step2, /myform/step3, etc) Creating components for each step that are dynamically lo ...

When encountering an issue while invoking a function in Vue.js, an internal error may occur, as evidenced by the message: "new Http

Currently, I am in the process of developing an application and encountering an issue where I am unable to comprehend a cryptic error message that keeps popping up. If you'd like to see the error itself, you can check it out here. Below is my form.vu ...

Encountering the "Local resource can't be loaded" error when attempting to link a MediaSource object as the content for an HTML5 video tag

I'm attempting to make this specific example function properly. Everything runs smoothly when I click the link, but I encounter an error when trying to download the HTML file onto my local machine and repeat the process. An error message pops up sayi ...

Route.get() function is expecting a callback function, but instead received a string object

Having searched through similar posts, I am unsure and lack the experience to apply the suggested resolutions to my project. I recently built a basic app with two main routes as part of a Udemy course, but I am struggling with the following error: "Route.g ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

Utilizing the code plugin in conjunction with Popcorn.js

I am currently exploring the world of Popcornjs and attempting to utilize the code plugin. However, I am facing some challenges in implementing it successfully. After following this example and managing to get the video to play, I found myself unable to e ...

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

Having trouble sending the information to Parse.com using the website

I am a beginner with the Parse database and I am currently working on implementing a code that allows users to sign up, with their information stored in the Parse database. However, I am encountering an issue where the values are not uploading as expected. ...

Disable the function when the mouse is moved off or released

My custom scrolling implementation in a ticker using Jquery is due to the fact that standard scrolling doesn't function well with existing CSS animations. The goal is to enable movement of the ticker when clicking and dragging on the controller, a div ...

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

Eliminate items from the array if the property of an object includes any of the provided substrings

In an attempt to minimize the objects within arrays that have a property "Title" containing any substring listed in a separate JSON file, I have been struggling with filtering the arrays based on the object's property. However, I believe using the red ...

Attempting to bring in an image file into a React component

My attempt to add an image at the top of my file failed, so I am looking for help with importing it. The code I originally tried did not work. The image does not display using the code below <img src={require('../../blogPostImages/' + post.bl ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...