0

Learning type script-- emp object is created at the end, but need to pass it inputData function to print the form data.

class empdata { public empid : number; public empname : string; public job : string; public leaves: number;

   constructor (empid : number, empname : string, job : string, leaves    : number){
     this.empid = empid;    this.empName= empName;    this.job=job;    this.leaves=leaves;   }
 
     inputData(){
 
   console.log(this.empname);
   console.log(this.job);
   console.log(this.leaves);
 
   }
    getFormData (){
     const form: HTMLFormElement = document.querySelector('#myform')!;
 
   form.onsubmit = () => {
   const formData = new FormData(form);
   const empName = formData.get('emp') as string;
   const job = formData.get('job') as string;
   const leaves = formData.get('leaves') as string;
   
   return false; // prevent reload    };    } } let emp = new empdata(1,"srikanth","manager",10); emp.getFormData();

emp.inputData();

1 Answer 1

1

You defined a function but did not call it. You can keep your definition in class (Not specifically in the constructor), and you can call it after your object creation like:

constructor(...)
{
  this.inputData();
}

inputData()
{
   console.log(this.empname);
   console.log(this.job);
   console.log(this.leaves);
}

//After your object creation
this.inputData(); // call again

UPDATE: From the comment, if you wish to update the values during object creation and during formdata value changes, you can make use of the same function inputData() to achieve this:

constructor(){
  this.empid = empid;
  this.inputData(empName, job, leaves);
}

inputData(empName, job, leaves){
  this.empName= empName;    
  this.job=job;    
  this.leaves=leaves; 
   
  console.log(this.empname);
  console.log(this.job);
  console.log(this.leaves);
}

// Afer updating form:
this.inputData(empName, job, leaves);
Sign up to request clarification or add additional context in comments.

2 Comments

let emp = new empdata(1,"srikanth","manager",10); is it necessary to pass data while creating object? i want to pass the form data.
Why do you want to create a new object with form data as new values? You can simply update this.empname, this.job, and this.leaves values inside your inputData() function itself and then console.log them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.