Display the array of selected values on the console upon clicking the submit button

After creating a function that saves checked values in the 'Arr' array, I am facing an issue where the array is being printed multiple times when the "View Results" button is clicked. This results in the checked values appearing multiple times on the screen when displayed in HTML. Is there a way to ensure that the result is printed only once when the button is clicked?

const list = Array.from(document.querySelectorAll(".form"));
const Arr = [];
const submitBtn = document.querySelector('.submit-button');

function check(e) {
  // a) When checked display result in array
  if (e.target.checked) {
    Arr.push(`${e.target.value}`);


    // b) When unchecked remove result from array
  } else if (!e.target.checked) {
    let index = Arr.indexOf(e.target.value);
    if (index != -1) {
      Arr.splice(index, 1)
    }
  }
  submitBtn.addEventListener('click', function() {
    console.log(Arr);
  })
}

list.forEach(function(listItems) {
  listItems.addEventListener('change', check)
})
<form class="form">
  <p> <u> Once you've checked the values below, check console to see value </u> </p>
  <br>
  <div class="list-items">

    <input type="checkbox" value="Item-1">Item-1
    <br>

    <input type="checkbox" value="Item-2">Item-2
    <br>

    <input type="checkbox" value="Item-3">Item-3
    <br>

    <input type="checkbox" value="Item-4">Item-4
    <br>

    <input type="checkbox" value="Item-5">Item-5
    <br>

    <input type="checkbox" value="Item-6">Item-6
    <br>

    <input type="checkbox" value="Item-7">Item-7
  </div>

  <div class="form submit">
    <h3 class="submit-message">Please click "View Results" to see your checked values in the console.
      <br>
      <button class="submit-button"><a href="#">View Results</a></button>
    </h3>
  </div>

Answer №1

To avoid multiple prints when the form is changed, remember to move the submitBtn.addEventListener outside the check method. Each time the form is changed, a new event listener is added, causing the issue you're experiencing.

const list = Array.from(document.querySelectorAll(".form"));
const Arr = [];
const submitBtn = document.querySelector('.submit-button');

function check(e) {
  // a) When checked display result in array
  if (e.target.checked) {
    Arr.push(`${e.target.value}`);

    // b) When unchecked remove result from array
  } else if (!e.target.checked) {
    let index = Arr.indexOf(e.target.value);
    if (index != -1) {
      Arr.splice(index, 1)
    }
  }
}
submitBtn.addEventListener('click', function() { // place this outside
    console.log(Arr);
});

list.forEach(function(listItems) {
  listItems.addEventListener('change', check)
})
<form class="form">
  <p> <u> Once you've checked the values below, check console to see value </u> </p>
  <br>
  <div class="list-items">

    <input type="checkbox" value="Item-1">Item-1
    <br>

    <input type="checkbox" value="Item-2">Item-2
    <br>

    <input type="checkbox" value="Item-3">Item-3
    <br>

    <input type="checkbox" value="Item-4">Item-4
    <br>

    <input type="checkbox" value="Item-5">Item-5
    <br>

    <input type="checkbox" value="Item-6">Item-6
    <br>

    <input type="checkbox" value="Item-7">Item-7
  </div>

  <div class="form submit">
    <h3 class="submit-message">Please click "View Results" to see your checked values in the console.
      <br>
      <button class="submit-button"><a href="#">View Results</a></button>
    </h3>
  </div>

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

A guide on displaying JSON response data in Angular JS with the help of ng-repeat

I am attempting to display the values of a specific JSON in the correct order. Here is how my JSON is structured : { "A":[{"id":"21","name":"Andrea"},{"id":"22","name":"Apple"}], "B":[{"id":"21","name":"Baby"},{"id":"22","name":"Bali"}], "C":[{"id":"21"," ...

What is the best way to implement the settimeout method in react?

I need assistance on how to effectively utilize the setTimeout() method in my code. Specifically, I am looking to trigger a click event on an element after a certain delay and execute a function afterwards. Here is the current implementation of my code: ...

Ensuring Code Execution Order in NODE.JS

I've encountered an issue with my code that involves parsing a pcap file, storing the data in an array data = [], and then writing it to a JSON file: var fs = require("fs"); var pcapp = require('pcap-parser'); var hex = ""; var data = []; v ...

Tips for connecting 2 Bootstrap 5 carousels

I currently have 2 Bootstrap 5 carousels (carousel-a & carousel-b) on the same page and I want them to be synchronized with each other. I believe this can be achieved using JavaScript, but I am not very familiar with it. Below is the structure of carousel- ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Instructions on opening a modal and changing the source of the iframe within the modal

I currently have a modal within my application that is triggered by Bootstrap: <div class="modal full-page fade" tabindex="-1" role="dialog" id="fullpageModal"> <div class="full-page-content"> <button type="button" class="close" d ...

updating dropdown options based on user input with PHP

I need help with implementing a code for two dropdown boxes. The first dropdown should display main category values dynamically, and when a value is selected, the second dropdown should appear with corresponding sub-category values. How can I achieve this ...

The jQuery change function appears to be functioning properly, but it is not producing any results

I am facing an issue with my jQuery code that rebuilds a dropdownlist based on the radio buttons selected. Although the code seems correct and the method works properly, the dropdownlist items do not update as expected. Can anyone provide some insight or i ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

Experiencing difficulties connecting with aspx while using Ext JS 4.2

Currently, I am facing an issue with making a call to an ASPX URL as the return keeps coming back as a failure. I have successfully used this URL in previous programming projects, but this is my first time utilizing it with Ext JS. Despite researching dif ...

Using React, TypeScript, and Next.js to transform all elements in a static array to their last occurrence

I'm having trouble updating my array. Every time I click the button for the second time, only two or more records are added, similar to the last one I added. Does anyone know how to fix this issue? In the images below, you can see the results of the ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

I am experiencing an issue where the position of the value in the returned response array keeps changing after an Ajax request is made. How can

I am currently using a script that sends an array of numbers through Ajax to a web server. These numbers are then used to query a database, and the corresponding values from the table are sent back. I then display these values in respective divs within my ...

I'm looking for a way to have an element shift in a particular direction only when two keys are pressed simultaneously

Having trouble moving a square diagonally when two keys are pressed simultaneously. Trying to create an if statement that detects both key presses at the same time and triggers the movement. However, all attempts have failed so far, leaving uncertainty abo ...

Presto SQL - What is the best method for obtaining every possible array combination?

Is there a way to generate all possible combinations of numbers from a given array? I attempted to use some built-in functions in presto like array_agg(x) Input : [1,2,3,4] Output when n=2 : [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] when n=3 : [[1,2,3],[1,2, ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

Retrieving the text of a selected option by its value

I need to create a menu that returns text based on a given value. For example, if the value is 0, I want it to return “zero”, and if it's 1, then “one”, and so on. I don't need to know which option is selected or auto-select anything, I j ...

Enhance the interoperability of Babel with Express.js by steering clear of relative

My current approach to imports is as follows: import router from '../../app/routes' Is there a way to avoid using ../../, for example: import router from 'app/routes'? In typescript, I can achieve this with the following configuratio ...