Course contentsShow
← React
Lesson 519 of 2,39614. Uncontrolled ComponentsFree lesson

Reading Values with event.target.elements

Access form elements directly through the submit event's target.elements collection by name or index.

Reading Values with event.target.elements

What you'll learn: How to access all form input values at once through the submit event's built-in elements collection.

The Core Idea

When a form submits, the event object gives you direct access to all form elements through event.target.elements. This collection lets you grab input values by name or index without needing individual refs for each field.

Think of event.target.elements like a filing cabinet built into every form—each drawer is labeled with the input's name attribute, and you can pull out any value you need instantly.

How It Works

function UncontrolledForm() {
  function handleSubmit(event) {
    event.preventDefault();
    
    // Access by name
    const username = event.target.elements.username.value;
    const email = event.target.elements.email.value;
    
    // Or by index (less common, order-dependent)
    const firstInput = event.target.elements[0].value;
    
    console.log({ username, email });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" defaultValue="johndoe" />
      <input name="email" defaultValue="john@example.com" />
      <button type="submit">Submit</button>
    </form>
  );
}

Why This Matters

This approach is cleaner than creating separate refs for each input. You simply ensure each input has a name attribute, then access them all through the single event object. It's particularly useful with uncontrolled components where you only need values at submission time.

Key Takeaway: The event.target.elements collection provides convenient name-based or index-based access to all form inputs during submission, eliminating the need for multiple refs in uncontrolled forms.