1

I would like to know if we can loop through event.target and get attribute values for each element inside a form. I am trying to implement this in Reactjs. There is just a basic form as given below

<form onSubmit={this.handleSubmit}>
    <input type="text" name="name" />
    <input type="email" name="email" />
    <input type="password" name="password" />
</form> 

and in the handleSubmit function, the code is as given below

handleSubmit(event) {
    event.preventDefault();

    let target   = event.target;
    let formData = {};

    formData.username = target.name.value;
    formData.email    = target.email.value;
    formData.passowrd = target.passowrd.value;

    console.log(formData);
}

I get the user filled data in the console.log as required. But as you can see I need specify each and every element to get the formData, Imagine a form with 20-30 elements.

I tried to do something as given below

count = 0;
formData = [];
foreach(target as item) {
    formData[count][item.name] = item.value;
}

It's basically PHP code But put here so that you can see what am trying to do. I tried to do this js and it gives me all kind of errors. Please let know if it's possible in js If so? How can I achieve it?

Pardeep
  • 2,153
  • 1
  • 17
  • 37
Scrappy Cocco
  • 1,192
  • 3
  • 21
  • 38

3 Answers3

4

I think u r looking for this:

handleSubmit(event) {
    event.preventDefault();

    let target   = event.target;
    let formData = {};

    for (let i = 0; i < target.length; i++) {
        formData[target.elements[i].getAttribute("name")] = target.elements[i].value;
    }
    console.log('formData', formData); 
}
Scrappy Cocco
  • 1,192
  • 3
  • 21
  • 38
Fahim Khan
  • 395
  • 2
  • 7
1

Sure you can. You cache all the inputs and then loop over them with forEach when the form is submitted.

// Cache the form element, and the inputs
const form = document.querySelector('form');
const inputs = form.querySelectorAll('input');

// Attach an event listener to the form that calls
// handleSubmit when it is submitted
form.addEventListener('submit', handleSubmit, false);

function handleSubmit(e) {

  // Prevent the form from submitting
  e.preventDefault();

  // Create a form object
  const form = {};

  // Iterate over your inputs and set the input name as your
  // property key, and the value as its value
  inputs.forEach(({ name, value }) => form[name] = value);
  console.log(form);
}
<form>
  <input type="text" name="name" />
  <input type="email" name="email" />
  <input type="password" name="password" />
  <button type="submit">Submit</button>
</form>
Andy
  • 61,948
  • 13
  • 68
  • 95
0

You can also use Array.from() to instansiate a new array from a form.

For example:

const handleOnSubmit = (event) => {
  event.preventDefault();

  const inputs = Array.from(event.target);

  inputs.forEach(input => {
    console.log(input.name, input.value);
  });
}
Camilo
  • 6,504
  • 4
  • 39
  • 60