Create "people" entities using the information provided in the input fields

I am looking for a way to automatically generate objects based on the data entered in the input fields.

I have already created a constructor function, but I am unsure about how to pass the data from the inputs to the constructor.

**My goal is to display the name, surname, age, and hobby on the screen.**

<div class="distribucion">
  <form class="form">
    <label for="nombre">Name:</label>
    <input type="text" id="nombre">
    <br>
    <label for="apellido">Apellido:</label>
    <input type="text" id="apellido">
    <br>
    <label for="edad">Edad: </label>
    <input type="text" id="edad">
    <br>
    <label for="hobbies">Hobbies:</label>
    <input type="text" id="Hobbies">
  </form>
  <div class="btns">
    <button id="send">Send</button>
    <button id="reset">Reset</button>
  </div>
</div>
* {
  margin          : 0;
  padding         : 0;
  outline         : 0;
  box-sizing      : border-box;
  font-family     : fantasy
  }
body {
  background-image: linear-gradient(#cc3290, #c41010);
  width           : 100%;
  height          : 100vh;
  display         : flex;
  justify-content : center;
  align-items     : center;
  }
.distribucion {
  display         : flex;
  flex-direction  : column;
  justify-content : space-around;
  align-items     : center;
  }
.form {
  width           : 250px;
  height          : 250px;
  box-shadow      : 0px 1px 50px #2a2a2a;
  border          : 1px solid #fff;
  border-radius   : 15px;
  color           : #fff;
  font-size       : 17px;
  padding         : 10px;
  display         : flex;
  flex-direction  : column;
  justify-content :space-evenly;
  }
.result {
  width           : 40%;
  height          : 15%;
  border          : 2px solid #fff;
  border-radius   : 10px;
  color           : #fff;
  padding         : 10px;
  }
.btns {
  width           : 90px;
  height          : 100px;
  display         : flex;
  flex-direction  : column;
  justify-content : space-evenly;
  border-left     : 15px;
  }
button {
  cursor          : pointer;
  border-bottom   : 10px;
  border-radius   : 15px;
  padding         : 5px 20px;
  letter-spacing  : 2px;
  background-color: transparent;
  }
#send {
  border          : 2px solid #fff;  
  color           : #050505;
  }
#reset {
  border          : 2px solid rgb(15, 15, 15);
  color           : #ffffff;
  }
let inpNom   = document.getElementById('nombre');
let inpApe   = document.getElementById('apellido');
let inpEdad  = Number(document.getElementById('edad'));
let inpHobb  = document.getElementById('Hobbies');
let btnSend  = document.getElementById('send');
let btnReset = document.getElementById('reset');
let result   = document.getElementById('text');

class Persona {
  constructor() {
      this.nombre   = inpNom.nodeValue;
      this.apellido = apellido;
      this.edad     = edad;
      this.hobbie   = hobbie;
  }
  copiar() {
    result.textContent = `Hola mi nombre es ${this.nombre} ${this.inpApe} mi edad es ${this.inpEdad}
    y me gusta mucho hacer ${this.inpHobb}.`;
  }
}

function createPerson() {
  let create = Persona.prototype.copiar();
}

btnSend.addEventListener('click',createPerson);

Answer №1

let inputName = document.getElementById('nombre');
let inputLastName = document.getElementById('apellido');
let inputAge = document.getElementById('edad');
let inputHobbies = document.getElementById('Hobbies');
let sendButton = document.getElementById('send');
let resetButton = document.getElementById('reset');
let resultText = document.getElementById('text');

class Person {
  constructor() {
    this.name = inputName.value;
    this.lastName = inputLastName.value;
    this.age = inputAge.value;
    this.hobbies = inputHobbies.value;
  }
}

function createPerson() {
  let newPerson = new Person
  resultText.textContent = `Hi, my name is ${newPerson.name} ${newPerson.lastName}, I am ${newPerson.age} years old, and I enjoy doing ${newPerson.hobbies}.`;
}

inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener("input", createPerson)
}

function clearInputs() {
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].value = ""
  }
  inputs[0].dispatchEvent(new Event("input"))
}
* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
  font-family: fantasy
}

body {
  background-image: linear-gradient(#cc3290, #c41010);
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.distribution {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}

.form {
  width: 250px;
  height: 250px;
  box-shadow: 0px 1px 50px #2a2a2a;
  border: 1px solid #fff;
  border-radius: 15px;
  color: #fff;
  font-size: 17px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.result {
  width: 40%;
  height: 15%;
  border: 2px solid #fff;
  border-radius: 10px;
  color: #fff;
  padding: 10px;
}

.buttons {
  width: 90px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  border-left: 15px;
}

button {
  cursor: pointer;
  border-bottom: 10px;
  border-radius: 15px;
  padding: 5px 20px;
  letter-spacing: 2px;
  background-color: transparent;
}

#send {
  border: 2px solid #fff;
  color: #050505;
}

#reset {
  border: 2px solid rgb(15, 15, 15);
  color: #ffffff;
}
<div class="distribution">
  <form class="form">
    <label for="name">Name:</label>
    <input type="text" id="nombre">
    <br>
    <label for="last name">Last Name:</label>
    <input type="text" id="apellido">
    <br>
    <label for="age">Age: </label>
    <input type="text" id="edad">
    <br>
    <label for="hobbies">Hobbies:</label>
    <input type="text" id="Hobbies">
  </form>
  <div class="buttons">
    <button id="reset" onclick="clearInputs()">Reset</button>
  </div>
</div>
Output:
<div id="text">Hi, my name is , I am  years old, and I enjoy doing .</div>

Answer №2

Isn't it amazing that FormData can directly create your object?

const myForm = document.forms['my-form']
  ,   ArrObj = []
  ;
myForm.onsubmit = e => 
  {
  e.preventDefault()
  
  ArrObj.push( Object.fromEntries(new FormData(myForm).entries()) )

  console.clear()
  console.log( ArrObj ) 
  }
* {
  margin          : 0;
  padding         : 0;
  outline         : 0;
  box-sizing      : border-box;
  font-family     : fantasy
  }
body {
  background-image: linear-gradient(#cc3290, #c41010);
  width           : 100%;
  height          : 100vh;
  display         : flex;
  justify-content : center;
  align-items     : center;
  }
.distribucion {
  display         : flex;
  flex-direction  : column;
  justify-content : space-around;
  align-items     : center;
  }
fieldset {
  width           : 250px;
  height          : 250px;
  box-shadow      : 0px 1px 50px #2a2a2a;
  border          : 1px solid #fff;
  border-radius   : 15px;
  color           : #fff;
  font-size       : 17px;
  padding         : 10px;
  display         : flex;
  flex-direction  : column;
  justify-content : space-evenly;
  }
.result {
  width           : 40%;
  height          : 15%;
  border          : 2px solid #fff;
  border-radius   : 10px;
  color           : #fff;
  padding         : 10px;
  }
.btns {
  width           : 90px;
  height          : 100px;
  display         : flex;
  flex-direction  : column;
  justify-content : space-evenly;
  border-left     : 15px;
  }
button {
  cursor          : pointer;
  border-bottom   : 10px;
  border-radius   : 15px;
  padding         : 5px 20px;
  letter-spacing  : 2px;
  background-color: transparent;
  }
button[type=submit] {
  border          : 2px solid #fff;  
  color           : #050505;
  }
button[type=reset] {
  border          : 2px solid rgb(15, 15, 15);
  color           : #ffffff;
  }

.as-console-wrapper { max-height:100% !important; top:0; left:50% !important; width:50%; }
.as-console-row         { background-color: yellow; }
.as-console-row::after  { display:none !important; }
<form name="my-form" class="distribucion">
  <fieldset>
    <label> Name:     </label> <input type="text" name="nombre"   ><br>
    <label> Apellido: </label> <input type="text" name="apellido" ><br>
    <label> Edad:     </label> <input type="text" name="edad"     ><br>
    <label> Hobbies:  </label> <input type="text" name="Hobbies"  >
  </fieldset>
  <div class="btns">
    <button type="submit"> Send  </button>
    <button type="reset" > Reset </button>
  </div>
</form>

If you are looking for a specific access method, just add:

ArrObj.get = i =>
  {
  if (i<ArrObj.length)
    {
    let el = ArrObj[i]
    return `Hello, my name is ${el.nombre} ${el.inpApe}, I am ${el.inpEdad} years old and I really enjoy doing ${el.inpHobb}.`
    }
  else return 'Out of range'
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

Keep the lock engaged during data input to prevent accidental slashes

Incorporating Symfony2.3.4, PHP5.6.3, Twig, HTML5, jQuery2.2.3, and CSS3. I am looking to implement a feature where the slashes (or separators in general) in an input field remain locked as the user enters numbers corresponding to the day, month, and year ...

What is the best way to adjust the camera position in ThreeJS while taking into account perspective?

Question: Currently, I am developing a first-person maze game using Threejs. I recently integrated DeviceOrientationControls to transition the game towards VR. However, I have encountered an issue where my previous camera movement system, which used arrow ...

Tips for avoiding a button reverting to its original state upon page refresh

I have a button with the ID #first that, when clicked, is replaced by another button with the ID #second. However, if I refresh the page after clicking on the second button, it goes back to displaying the first button. Is there a way to make sure that th ...

Save the output of my Java function into a JavaScript variable

I have created a web application using JSP, CSS and HTML. The page contains six buttons, each of which calls a JavaScript method. For instance, the first button triggers the par() method. <html> <head> <title>Welcome d To Student Unive ...

Tips for waiting for image to finish loading from success data of an ajax() call?

I am utilizing the jquery ajax() function: $.ajax({ type: "POST", url: 'ajax.php', data: 'url='+variable, success: function(data){ $('#mydiv').html(data); } }); The ajax response (data variable) I ...

Content briefly appears and then vanishes with the use of ng-if

On my webpage, I have content that is enclosed in an ng-if directive as shown below: <div ng-if="ShowMessgae" class="text-danger"> <p> <strong> Message displayed to User </strong> </p> < ...

What is causing my div exchange using .class to fail?

Struggling to convert this code from working with IDs to Classes. The code reveals one Div while hiding another based on the onClick event. Originally, it was straightforward because the div location was absolute. In the classes version, I need to revea ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

How can I utilize passed in parameters in Meteor React?

I am trying to figure out how to use two params that I have passed in the following example. Can someone please assist me? updater(layer, item){ this.setState({layer5: <img id="layer5" className="on-top img-responsive center-block" name="layer5" ...

Selecting elements on a new window using jQuery

I'm having a challenge with accessing elements in a new window that is opened using $window.open() : var printWindow = window.open(window.location.href, 'Imprimer', config = 'width=1024, toolbar=no, menubar=no, scrollbars=yes, resizabl ...

What is the best method for ensuring that my JavaScript tracking script has been properly installed on the customer's website?

We provide a SAAS analytics application that functions similarly to Hotjar and Google Analytics. To track user data, our customers must integrate our JavaScript code into their websites. How can we confirm if the script has been successfully integrated in ...

Using the POST method allows for sending a distinct string from REACT to an API

I am experiencing an issue with my SQL query component. Whenever I send a query to the API-server, the backend crashes because MySQL interprets an empty string as my request. Interestingly, my backend works perfectly fine when tested using postman.exe. T ...

Easy Access Form

I am working on creating a straightforward login form using HTML and JavaScript. The goal is to verify the entered username and password against a set list of authorized credentials upon submission. If the input credentials are correct, I want to direct t ...

What is the best way to implement date range filtering in vue js?

Currently, I am delving into the realm of vue.js and experimenting with a filtering feature that involves date ranges. The process goes like this: initially filter by type, then proceed to filter by a specified date range, consisting of start and end dat ...

Selector in CSS targeted by using target selector

When you click on the anchor tag "Click me," is there a way to use only CSS to display the p tag with the text "This is my answer"? I am aware that placing the p tag after the anchor tag is a solution, but I am curious if there is a method to achieve this ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

The default locale for momentJS is set to zh-tw and I'm having trouble changing it

Currently, I am incorporating the momentJS library into my Angular application by pulling it from a CDN: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script> Although the default locale should be Engli ...

Develop a scrambled PHP webpage for a CAPTCHA system

I've implemented the cool-captcha feature in my registration form. Here's the code snippet that generates the Captcha image: <img src="captcha.php" id="captcha" /> However, there is an issue where anyone can easily access the "captcha.ph ...