简体   繁体   中英

How to call a method from a class using a button?

I am getting a reference error "addCharacter not defined". Not sure what I need to change? The goal is that when a user types in a name and age, an hits submit, it saves the character to an array. Here is what I have so far:

<input id="inputName" type="text" placeholder="Name" value="John">
<input id="inputAge" type="text" placeholder="Age" value="20">
<button onclick="addCharacter()">Submit</button>
//Create Class
class Character {
  name = document.getElementById("inputName").value;
  age = document.getElementById("inputAge").value;

  //Method
  addCharacter = () => {
    let characterList = [];
    characterList.push(this.name, this.age);
    console.log(characterList);
  };
}

//Store instance in variable
const myCharacter = new Character();

//Execute
myCharacter.addCharacter();

https://codepen.io/lacheporter/pen/jOVQmqp?editors=1111

I just made it a function that does what I want, so I hope it helps others. I was creating a class for something that could be done with a simple function. It was mostly for learning purposes. Not sure I see the point in classes?

<input id="inputName" type="text" placeholder="Name" value="John">
<input id="inputAge" type="text" placeholder="Age" value="20">
<button onclick="addCharacter()">Submit</button>
let characterList = [];


function addCharacter(){

 let name = document.getElementById("inputName").value;
 let age = document.getElementById("inputAge").value;

characterList.push(name, age);
console.log(characterList);
 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM