"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

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Configuring RingoJS to search for necessary modules within the node_modules folder

Currently, I am in the process of transitioning a service from nodejs to ringojs. My main hurdle involves the usage of require(). To illustrate, take a look at this snippet: var restify = require('restify'); The issue arises when RingoJS is una ...

Learn how to create a stunning effect by combining two half images and revealing a full image upon hover with a smooth animation

I am struggling with implementing a specific feature using jQuery. I have designed a page hero with two sections (red and black): My goal is to have the black section expand over the red section when hovering, creating a full black box. I want the same ef ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

Why is it that using e.preventDefault() does not prevent the link from being followed?

What is the solution to prevent a link from being followed with this specific event handler? http://jsfiddle.net/chovy/rsqH7/1/ <table> <tbody> <tr class="msg"> <header><a href="http://cn ...

JS glitch leading to oversized window dimensions - Issue with dropdown menu

I recently integrated a dropdown into my website using Foundation CSS. To see the dropdown in action, you can login with the credentials provided (username: stackoverflow password: testtest) on . However, I noticed that when logged in, the page on the rig ...

I encountered the following error: Failed to parse due to the module '@babel/preset-react' being missing

Encountering a parsing error: Module '@babel/preset-react' cannot be found. Upon creating schema.js, tweetSchema.js, userSchema.js, issues arose with import, export, and export from all three files showing red lines. schema.js: import createSche ...

implementing AJAX functionality in Laravel when a drop-down item is selected

Hello there, I am a newcomer to the world of coding and I'm currently learning Laravel for a personal project. My goal is to retrieve data from a database based on the selection made in a dropdown menu. Here's the code for the dropdown menu: < ...

What is the best way to convert my Chatbot component into a <script> tag for seamless integration into any website using React.js?

I have successfully integrated a Chatbot component into my Next.js application. https://i.stack.imgur.com/BxgWV.png Now, I want to make this component available for anyone to use on their own website by simply adding a tag. My initial approach was to cre ...

What are the steps to store my information in MongoDB with the help of Expressjs?

As a backend developer beginner, I am currently working with an array called Movie using expressJS. My goal is to save this array in a MongoDB database, specifically using Mongodb Atlas. Any help or guidance on this process would be greatly appreciated. I ...

Learning the process of utilizing Json in Flot to create visually appealing graphs

I'm currently utilizing the Flot Graph Api to showcase bar charts and line charts on my client-side PHP environment. I am attempting to pass Json data to plot the graph as outlined in their examples. This is how I structure the Json data: [{"label": ...

An unanticipated issue has arisen with the Alert Open Error. The command "browser.switchTo().alert().accept();" functions properly in Firefox, but encounters difficulties in Chrome while executing via Jenkins

Seeking assistance on how to resolve a specific error encountered in the Chrome browser while using Protractor. https://i.stack.imgur.com/7Fm4l.png The error message reads as follows: "UnexpectedAlertOpenError: unexpected alert open: {Alert text : There a ...

Developing a customizable datepicker with the ability to select specific months or date ranges

I am currently developing a WebApp using flask and constructing templates in HTML/JS for the front end. I am in need of a datepicker that will provide the user with the option to choose a specific date range or select a range of months. Take a look at the ...

Contrast: Colon vs. Not Equal Sign (Typescript)

Introduction Hello everyone, I am new to Typescript and currently grappling with some fundamental concepts. When defining a parameter for a function, I typically specify the type like this: function example(test: string){...} However, as I delve deeper ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

What is the best method for conducting comprehensive testing of all projects and libraries within NestJS (nx)?

Our NestJS project has been established with multiple libraries through Nx. We have successfully run tests on individual projects/libraries using the following command: npx nx test lib1 --coverage While this method works well, we are faced with numerous l ...

"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses [ { "id": 0, "title": "Coop.Sociale Prassi e Ricerca Onlus", "latitude": 0, "longitude": 0, "address": "Viale Eleonora D'Arborea 12, Roma, IT" }, { "id": 0, "title": "San Lorenzo", "lati ...

Vue template is not being rendered when served through Django

I am currently working on a Django application where Vue is used as the frontend to render templates. In my Django view code, I have the following components: # thing/views.py def index(request): template = loader.get_template('thing/index.html&a ...