Home > database >  How can i collect data from form with javascript and store it in variables?
How can i collect data from form with javascript and store it in variables?

Time:06-05

Hey lets say i have a simple form like this:

<form>
<label for="name">Enter name:</label>
<input type="text" id="name">
<label for="surname">Enter surname:</label>
<input type="text" id="surname">
<label for="number">Phone number:</label>
<input type="text" id="number">
</form>

and in javascript, instead of getting values one by one and storing them with queryselectors, is there a way i can select the whole form and get its input values? also after that how can i store them in variables so i can use them later? for example, print them one by one.

CodePudding user response:

Bobi. You may use javascript FormData() method.

var formData = new FormData(document.querySelector('form'))

Please check this document. https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

Hope this helps. Happy coding~ :)

CodePudding user response:

You can use FormData:

let myForm = document.getElementById('myForm');
let formData = new FormData(myForm);
console.log(formData.entries());
<form id="myForm">
  <label for="name">Enter name:</label>
  <input type="text" id="name">
  <label for="surname">Enter surname:</label>
  <input type="text" id="surname">
  <label for="number">Phone number:</label>
  <input type="text" id="number">
</form>

  • Related