"JavaScript function to add objects to an array when button is clicked

var householdData = [];

function createMember(age, relationship, smoker) {
  this.age = age;
  this.relationship = relationship;
  this.smoker = smoker;
}

addBtn.addEventListener("click", addHouseholdMember);
  
function addHouseholdMember() {

      var selectedAge = "EaxampleData";
      var selectedRelationship = "ExampleData";
      var selectedText = "ExampleData";
      var selectedSmoker = "ExampleData";
  
      var currentMember = new createMember(selectedAge, selectedText, selectedSmoker);
      console.log(currentMember);
      return householdData.push(currentMember);
  
};

I am attempting to add the object I've created to an array. Although I can log the object when the button is clicked, I'm unable to return anything out of the click function. I realize I must be missing something simple, but I haven't been able to figure out what it is.

Answer №1

I am attempting to add the object I have generated into an array.

The object is successfully added, confirming that your code is functioning as expected

When the button is clicked, I can log the object to the console, but I am unable to return anything from the click function.

To see the updated array, try printing it out in a console.log statement like in this example:

var householdData = [];

function householdMember(age, rel, smoker) {
  this.age = age;
  this.rel = rel;
  this.smoker = smoker;
}

document.getElementById("button").addEventListener("click", addHouseholdMember);

function addHouseholdMember() {
      var selectedAge = "28";
      var selectedRel = "25";
      var selectedText = "22";
      var selectedSmoker = "21";
      var currentHouseholdMember = new householdMember(selectedAge, selectedText, selectedSmoker);
      console.log(currentHouseholdMember);
      console.log(householdData);
      return householdData.push(currentHouseholdMember);
     
};
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button id="button">CLICK</button>
</body>
</html>

It's important to note that there is a missing semicolon in your code here

var selectedAge = "ExampleData <--;

Your approach of assigning a callback to the click event, creating a new object using the householdMember function with the appropriate parameters, and then pushing the new object to the array is correct.

Answer №2

Correct the selectedAge data (closing quote) and retrieve the updated value, rather than the push outcome.

function addHouseholdMember() {

  var selectedAge = "SampleData";
  var selectedRel = "ExampleData";
  var selectedText = "ExampleData";
  var selectedSmoker = "ExampleData";

  var currentHouseholdMember = new householdMember(selectedAge, selectedText, selectedSmoker);
  console.log(currentHouseholdMember);
  householdData.push(currentHouseholdMember);
  return currentHouseholdMember;

};

Answer №3

Transfer the task of pushing data to the householdMember by implementing a new function

Rather than printing out the value, consider returning it instead

var addBtn = document.getElementById('btn')
var householdData = [];

function householdMember(age, rel, smoker) {
  this.age = age;
  this.rel = rel;
  this.smoker = smoker;
  this.addVal = function() {
    householdData.push({
      age: this.age,
      rel: this.rel,
      smoker: this.smoker
    })
    return householdData;
  }
}

addBtn.addEventListener("click", addHouseholdMember);

function addHouseholdMember() {

  var selectedAge = "EaxampleData";
  var selectedRel = "ExampleData";
  var selectedText = "ExampleData";
  var selectedSmoker = "ExampleData";

  var currentHouseholdMember = new householdMember(selectedAge, selectedText, selectedSmoker);
  console.log(currentHouseholdMember.addVal())
};
<button id='btn'>Click</button>

Answer №4

It seems like there is an unterminated string constant in this code snippet. You need to add the closing quotation mark and try again.

  var householdData = [];
var addBtn = document.querySelector('.addBtn');
function householdMember(age, rel, smoker) {
  this.age = age;
  this.rel = rel;
  this.smoker = smoker;
}

addBtn.addEventListener("click", addHouseholdMember);

function addHouseholdMember() {
      var selectedAge = "EaxampleData";
      var selectedRel = "ExampleData";
      var selectedText = "ExampleData";
      var selectedSmoker = "ExampleData";

      var currentHouseholdMember = new householdMember(selectedAge, selectedText, selectedSmoker);
  householdData.push(currentHouseholdMember);
console.log(householdData);
};
<a class='addBtn'>add</a>

You can view a working example of this code here.

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

What could be causing the undefined status of this length function?

I need to determine the length of seconds. If the second is only one character long, I want to add a 0 in front of it. Otherwise, no action is needed. Below is my code: <p>Click the button to show the current number of seconds.</p> <p id= ...

Error in Next.js: .env variable not defined

I recently transitioned my project from React to Next.js and encountered an issue where my environment variables are showing as undefined, even though they were functioning correctly in React. Can someone provide some guidance or assistance with this probl ...

Why does the Vue router sometimes refresh the page instead of properly navigating to it? Can you spot the difference between these two code examples?

I am encountering an issue while trying to click on a "checkout" button that is supposed to send cart data to a backend and redirect me to a URL generated by the backend. Despite receiving a valid URL, my code is not functioning correctly. When I attempt ...

What is the best way to dynamically select and deselect radio buttons based on a list of values provided by the controller?

I am currently working on implementing an edit functionality. When the user initially selects a list of radio buttons during the create process, I store them in a table as a CSV string. Now, during the edit functionality, I retrieve this list as a CSV stri ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? Here's my HTML code: <mat-form-field appearance="outline" fxFlex=" ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

After the build process, Nextjs Sitemap is eliminating the /en/ from all newly generated web links

Utilizing Strapi to pull data in JSON format. For instance, a typical website link appears as follows: https:/ /www.some-site.com/some-link What happens to the links once the post build is completed on my Nextjs project: <url><loc>https://web ...

Creating a custom PHP webpage and integrating it with a WordPress theme

I'm looking to develop a unique php and javascript page that is integrated with my existing Wordpress theme. Can anyone provide guidance on how to achieve this? Appreciate the help! ...

Issue with Translate3d functionality in fullpage.js not functioning as expected

Currently, I am in the process of constructing a website using fullpage.js with WordPress. Everything is functioning well except for one issue - when attempting to disable the plugin by using destroy() or changing setAutoScrolling to false, the translate3d ...

Ways to incorporate a scroll feature and display an iframe using JQuery

Is there a way to animate the appearance of hidden iframes one by one as the user scrolls down the website using jQuery? I have come across some solutions, but they all seem to make them appear all at once. I'm looking for a way to make the iframes s ...

Combining two request.get functions into a single one

Is there a way to combine these two functions into one? I have two APIs: /page1 and /page2. My goal is to merge the two arrays into one because the GitHub API only displays 100 objects per page. request.get({ url: 'https://api.github.com/users/an ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

Binding Events to Elements within an AngularJS-powered User Interface using a LoopIterator

I am working with an Array of Objects in AngularJS that includes: EmployeeComments ManagerComments ParticipantsComments. [{ "id": "1", "title": "Question1", "ManagerComment": "This was a Job Wel Done", "EmployeeComment": "Wow I am Surprised", ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

I am struggling to send an email using PHP mailer with POST data

i'm facing challenges with integrating phpmailer and ajax. As a beginner in ajax, I still have some gaps in understanding the concept. When I directly run my php mailer script on a page with preset values, I can successfully send out an email. However ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

``So, you're looking to retrieve a collection of objects that have a OneToMany

Is there a way to retrieve a list of objects with a OneToMany relation using TypeORM's queryBuilder? This is the desired output: { "id": 1, "firstName": "Bob", "lastName": "Sparrow", "orders": [ { "id": 1, "name": "Very Big Or ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

I aim to showcase particular cookies within an input field using jQuery

I am seeking a way to create a responsive page that showcases cookies. My goal is to have the output of a function automatically appear in the input value upon loading the page, instead of requiring a click event. Here is the code snippet I have been worki ...