0

I have 3 buttons in my HTML file with the same onclick function name

    <button id="name 1" onclick="choice()">John</button>
    <button id="name 2" onclick="choice()">Martin</button>
    <button id="name 3" onclick="choice()">Sam</button>

and a JS file that makes a list out of the buttons names and each name has a point property set to 0

 let characters = [
   {name: document.getElementById("name 1").textContent, points: 0},
   {name: document.getElementById("name 2").textContent, points: 0},
   {name: document.getElementById("name 3").textContent, points: 0}
];

is there a way I can make a function unique even with a mutual name so that when i click on that button, it runs a function related to that button only (for my case clicking on John adds a point to him only and no one else). Also, how do i change the number of the points property so that every time i click on a button it adds 1 point

2 Answers2

1

Yeah you could make a function that runs unique for each button.

Hope this helps:

one way is :-> You could parse the button element as an argument to the choice function

let characters = [
   {name: document.getElementById("name 1").textContent, points: 0},
   {name: document.getElementById("name 2").textContent, points: 0},
   {name: document.getElementById("name 3").textContent, points: 0}
];


function choice (button) {
  const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
  buttonCharacterObject.points += 1;
  
  console.log(characters)
}
<button id="name 1" onclick="choice(this)">John</button>
<button id="name 2" onclick="choice(this)">Martin</button>
<button id="name 3" onclick="choice(this)">Sam</button>
Rilla
  • 505
  • 4
  • 16
0

You can pass a parameter to the function and then treat this parameter to perform a specific action. The function statement will look like this:

choice(parameter){
  if(parameter == "John"){
    characters[0].points = characters[0].points++;
  } else if(parameter == "Martin"){
    characters[1].points = characters[1].points++;
  } else{
    characters[2].points = characters[2].points++;
  }
}

And you can call like this:

<button id="name 1" onclick="choice("John")">John</button>
<button id="name 2" onclick="choice("Martin")">Martin</button>
<button id="name 3" onclick="choice()">Sam</button>

Something like this will help you.