javascript array push not functioning as expected

I have written some JavaScript code that is supposed to add another element with a value of 1 when I click a button. However, currently it is resetting the array so only one element gets added each time. How can I fix this issue?

 var x = document.getElementsByTagName('button');//return button array
 var age_array = [];
  smoker_array = [];
  relation_array = [];

  age = 0;

//add button clicked
x[0].addEventListener("click", function(){

   /*
   var age = document.getElementsByName("age")[0].value;//pull age from box
   var relation = document.getElementsByName("rel")[0].value;//pull relation
   let smoker = document.querySelector('[name=smoker').checked;

   //check relation 
   if(relation === "")
   {
       alert("please select a realation"); 
   }

   //check to see if age < 0
   if(age < 0 || age === " ")
   {
       alert("age not applicable");
   }
    */


  age_array.push(1);
  alert(age_array.length);


});

/*function submit(age, relation, smoker)
{
   age_array.push(age);

    alert(age_array[0]);
    alert(age_array[1]);
    /*
    x[1].addEventListener("click", function(){
       var age = JSON.stringify(entry_age);
       alert(entry_age[1]);
       document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
       document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);  
    });
}
    */

Below is the HTML code for reference:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8>
        <title>Household builder</title>
        <style>
            .debug {
                font-family: monospace;
                border: 1px solid black;
                padding: 10px;
                display: none;
            }
        </style>
    </head>
    <body>
        <h1>Household builder</h1>
        <div class="builder">
            <ol class="household"></ol>
            <form>
                <div>
                    <label>Age
                        <input type="text" name="age">
                    </label>
                </div>
                <div>
                    <label>Relationship
                        <select name="rel">
                            <option value="">---</option>
                            <option value="self">Self</option>
                            <option value="spouse">Spouse</option>
                            <option value="child">Child</option>
                            <option value="parent">Parent</option>
                            <option value="grandparent">Grandparent</option>
                            <option value="other">Other</option>
                        </select>
                    </label>
                </div>
                <div>
                    <label>Smoker?
                        <input type="checkbox" name="smoker">
                    </label>
                </div>
                <div>
                    <button class="add">add</button>
                </div>
                <div>
                    <button type="submit">submit</button>
                </div>
            </form>
        </div>
        <pre class="debug"></pre>
        <script type="text/javascript" src="index.js"></script>
    </body>
</html>

Answer №1

Perhaps the issue lies in the fact that your code may not be compatible with strict mode.

var age_array = [];
    smoker_array = [];
    relation_array = [];

You could try writing it like this:

var age_array = [],
    smoker_array = [],
    relation_array = [];

Alternatively, you can structure it as follows:

var age_array = [];
var smoker_array = [];
var relation_array = [];

Answer №2

Hello everyone, I just wanted to express my gratitude for the assistance I have received here. It appears that there is an issue with the HTML code, although I am unsure of what specifically. Despite this obstacle, I was able to successfully implement JavaScript using a different HTML structure as I am unable to modify the existing one. Once again, thank you all for your help.

I will now mark this question as resolved.

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

Shadows are mysteriously absent in the 3D scene despite having the castShadow and receiveShadow properties enabled

View image description here Hello, I'm facing an issue with the shadows in my 3D model. Even though I have enabled shadow casting and receiving in the code, the shadow is not appearing on my model. You can reference the provided image or visit this ...

Identifying browser compatibility with thick WebGL lines

According to the documentation provided by three.js: Due to limitations in the ANGLE layer, when using the WebGL renderer on Windows platforms, linewidth will always be set to 1 regardless of the specified value. Wide lines may not work in certain brow ...

Tips for enforcing validation rules at the class level using Angular's version of jQuery Validate

After utilizing jQuery Validate's convenient addClassRules function to impose a rule on all elements of a specific class, rather than relying on the attributes of their name, I encountered a roadblock when trying to do the same with the Angular wrappe ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

the JavaScript anchor feature is malfunctioning

Steps to Play Back: To start, in the header section, select any of the links with anchors: ##bankaccount #pack #platform #acq ##scorecard ##intrade #form Next, scroll up to the top of the page Then, reload the page Actual Outcome: Upon reloading a page w ...

Initiate a file download following the redirection of a user to a new page in NodeJS/Express

Overview I am currently developing a NodeJS project using Express. In the application, there are buttons visible to the public that trigger file downloads. These buttons are linked to protected routes which will redirect users to a login page if they are ...

Iterating through a JSON object using an API loop

Just starting out in JS and I am attempting to use a for loop to combine all the 'text' from various JSON objects into one cohesive paragraph. For example, it should read like this: "Hello, and welcome to the Minute Physics tutorial on basic Rock ...

Disable the button on page load condition

In the Mysql PHP setup, there is a page displaying a list of students with student_id, name, birthdate, and various buttons on each row. The objective is to make a certain button inactive if the student_id is found in another table called 'saral_tciss ...

Showing hidden JavaScript elements in different parts of a webpage

Update: After making modifications to my JavaScript code, I am now encountering errors in the iPhone Debug Console. Disclaimer: As a newcomer to web development, I have limited expertise in JavaScript. Situation: My current project involves creating an e ...

How can we use Mongoose .find to search with an array stored in req.params and respond with an array containing each value along with its

It would be great if a user could input multiple tags in a search field, and have them separated client-side (before making the .get call) to send over ajax with each keypress. While testing the API with Postman on the server-side, if the .get method retu ...

An error is thrown when using less.js

Every time I attempt to add less.js, I encounter an XmlHttpRequest Exception 101. Including the .less file is done using this method: <link rel="stylesheet/less" type="text/css" href="anything.less" /> This issue only arises when I upload the th ...

Scroll through like Uber Eats with horizontal ScrollSpy and navigation arrows

I am in need of a menu style similar to Uber Eats, with an auto horizontal scroll feature for categories that exceed the available width. Additionally, I would like the active links in the menu to change as the user scrolls down, reflecting the current cat ...

Error in Node.js: Using `import` token incorrectly

I am having trouble figuring out what the issue is. Node v5.6.0 NPM v3.10.6 This is the code snippet: function (exports, require, module, __filename, __dirname) { import express from 'express' }; The error message reads: SyntaxError: Une ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Extract user's location using JavaScript and transfer it to PHP

My goal is to utilize JavaScript to retrieve the latitude and longitude, then compare it with the previous location, similar to how Facebook authenticates logins from different devices. To accomplish this, I have implemented 2 hidden fields which will capt ...

The AJAX call is not being identified correctly

I am facing an issue with my search result pagination wherein the page reloads instead of loading via AJAX when using the pagination. The search results are correctly loaded through partial view with AJAX, but the pagination triggers a non-ajax request cau ...

Troubleshooting React child problems in TypeScript

I am facing a coding issue and have provided all the necessary code for reference. Despite trying numerous solutions, I am still unable to resolve it. export class JobBuilderOptimise extends React.Component<JobBuilderOptimiseProps & JobBuilderOptim ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

Deactivating an emitted function from a child component in Angular 4

There is a main component: @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { funcBoo():void{ alert("boo"); //return fal ...

What is the best way to activate a click event within an ng-repeat loop in AngularJS

Is there a way to trigger an event click handler in angular where clicking the button will also trigger the span element? I've tried using the nth-child selector without success. Any suggestions on how to achieve this? I also attempted to use jQuery s ...