I want to add object to an array each time I clicked the button.
let data = [];
function add() {
data.push({ data: 5, data1: 10});
}
expected if clicked 3 times
data = [{ data: 5, data1: 10}, { data: 5, data1: 10}, { data: 5, data1: 10}]
CodePudding user response:
If I understand correctly, you're trying to figure out how to create a button that will add that data to the array every time it is clicked. You can do this in one of two ways:
The first way is by adding the onClick="{insert desired function here}"
attribute to whichever element you want to run the function after being clicked (i.e. <div onClick="add()">
).
Note: Make sure you reference the JavaScript file in the head of the HTML code by using <script src="{insert file path here}"></script>
.
The second way is by adding an event listener to the code in JavaScript. You can do this by declaring your button element(s) as a variable and then adding an event listener to it that listens for a click. By wrapping that in a 'for' loop you can have as many buttons that do this as you want, as long as they have the same class. I've provided an example below:
var buttons = document.getElementsByClassName('addButton')
for (i = 0; i < buttons.length; i ) {
buttons[i].addEventListener('click', add)
}
let data = [];
function add(event) {
data.push({ data: 5, data1: 10});
console.log(data)
}
<!DOCTYPE html>
<html>
<head>
<script src="{insert file path here}"></script>
</head>
<body>
<div >Click Me</div>
</body>
</html>
CodePudding user response:
Your add function needs a handler for the 'click' event so that when you click on your button or HTML element it runs the function to add the object to the array,
right now your function isn't being called.
<body>
<button id="btn" onclick="add()"></div>
</body>
or
var btn = document.getElementById('btn')
btn.addEventListener('click',add)