We can use the FormData
constructor to create an object that gets the key-value pairs of the form values we entered.
For instance, if we have the following form:
<form>
Credit Card Validation:
<input type="text" name="cctextbox">
<br />
Card Type:
<select name="cardtype">
<option value="visa">Visa</option>
<option value="mastercard">MasterCard</option>
<option value="discover">Discover</option>
<option value="amex">Amex</option>
<option value="diners">Diners Club</option>
</select>
<br />
<input type="submit" />
</form>
Then we can write:
const form = document.querySelector('form')
form.addEventListener('submit', (e) => {
e.preventDefault()
const formData = new FormData(form)
for (const pair of formData.entries()) {
console.log(pair)
}
})
to listen to the submit event of the form and get the value when we submit.
We first get the form element with document.querySelector
.
Then we call addEventListener
to add the submit event listener to the form.
The 2nd argument of addEventListener
is the submit event listener.
We call e.preventDefault
to prevent the default submit behavior so we can do client-side form submission.
Then we create the formData
object with the FormData
constructor with the form
as the argument to get the form data values.
And then we call formData.entries
to get an array of form data key-pair pairs.
Then pair
should be something like:
["cctextbox", "aa"]
["cardtype", "visa"]
where the first entry if the name
attribute value and the 2nd entry is the entered value.