Categories
JavaScript Answers

How to get values from inputs and create an array with JavaScript?

Spread the love

Sometimes, we want to get values from inputs and create an array with JavaScript.

In this article, we’ll look at how to get values from inputs and create an array with JavaScript.

How to get values from inputs and create an array with JavaScript?

To get values from inputs and create an array with JavaScript, we can get all the inputs and get each input’s value from the value property.

For instance, we write:

<form>
  <input type="text">
  <input type="text">
  <input type="text">
  <input type='submit'>
</form>

to add a form.

then we write:

const form = document.querySelector('form')
const input = document.querySelectorAll('input[type="text"]')
form.onsubmit = (e) => {
  e.preventDefault()
  const arr = [...input].map(i => i.value)
  console.log(arr)
}

to select the form with querySelector and select the text inputs with querySelectorAll.

Then we set the form.onsubmit property to a function that runs when the form is submitted.

In the function, we call e.preventDefault to prevent the default server side form submission behavior.

Then we get all the input values by spreading the inputs into an array and call map with a callback that returns the value property of each input.

As a result, when we submit the form with input values, we see them logged.

Conclusion

To get values from inputs and create an array with JavaScript, we can get all the inputs and get each input’s value from the value property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *