简体   繁体   中英

How can i pass html input data to a javascript class

I am trying to pass data from html input to a vanilla JS class constructor. this is what I have tried.

class Users {
  constructor(email,password) {
    this.email = email;
    this.password = password;

  }


  login(){
      // url for endpoint
let url = "http://127.0.0.1:5000/api/v2/users/login"

alert(this.password)

// get login data from ui
let data = {
  email : this.email,
  password : this.password
};

}
let email = document.getElementById('email').value,
let password = document.getElementById('password').value
const user = new Users(email,password)
document.getElementById('login').addEventListener('submit', user.login())

It seems no data is passed to the email and password variables.

I have also tried to do this but the object is not called

class Users {
  constructor(email,password) {
    this.email = email;
    this.password = password;

  }

        login(){
    // user the data here

}
function load(event){
   let email = document.getElementById('email').value,
   let password = document.getElementById('password').value
   const user = new Users(email,password)
   user.login()
}

document.getElementById('login').addEventListener('submit', load)

Someone help me on how to work on this.

I have tried my best to refactor your code. Depending on what you want to do with the data, thats up to you. But in the below code, you can get the email and password in the login function

 class Users { constructor() { } login(){ let email = document.getElementById('email').value, password = document.getElementById('password').value alert(email, password) } } const user = new Users(); const login = user.login 
 <input type="text" id="email" /> <input type="text" id="password" /> <button id="login" onclick="login()">submit</button> 

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