[HTML 5] Access form and elements

import './assets/css/style.css';

const app = document.getElementById('app');
app.innerHTML = `
  <h1>JavaScript DOM</h1>
  <form name="order">
    <label>
      Your name
      <input type="text" name="fullname">
    </label>
    <label>
      Your email
      <input type="text" name="email">
    </label>
  </form>
`;

const form = document.forms.order;

const {fullname, email} = form.elements;

function handleInput(event) {
  // access the value
  console.log(event.target.value);

  // access the form
  console.log(event.target.form);
}

fullname.addEventListener('input', handleInput);

 

1. You can use document.forms to access form, by given form a name, you can access that form by name

const form = document.forms.order;

 

2. Inside event handler, you can also get form reference by:

  // access the form
  console.log(event.target.form);

 

3. Access the elements of the form:

const {fullname, email} = form.elements;

 

posted @ 2020-06-17 20:26  Zhentiw  阅读(222)  评论(0编辑  收藏  举报