Processing the form in JavaScript

Explore the basics of using forms in HTML and JavaScript

Forms are an extremely important part of HTML and Web platforms. They allow users to interact with the page, and

  • Search for content on the site
  • Trigger the filter to trim the result page
  • send Message

there are more.

By default, the form submits its content to the server-side endpoint, which by default is the page URL itself:

<form>
  ...
  <input type="submit">
</form>

We can setactionThe attributes of the form element, used bymethodAttribute, default isGET:

<form action="/contact" method="POST">
  ...
  <input type="submit">
</form>

After clicking the submit input element, the browser sends a POST request/contactURL on the same source (protocol, domain and port).

Using JavaScript, we can intercept this event and submit the form asynchronously (usingXHRwithBring it), we can also react to events that occur on a single form element.

Intercept form submission events

I just described the default behavior of forms without JavaScript.

In order to start using JavaScript to process forms, you need to interceptsubmitEvents on form elements:

const form = document.querySelector('form')
form.addEventListener('submit', event => {
  // submit event detected
})

Now in the Submit event handler function, we willevent.preventDefault()Ways to prevent default behavior and avoid form submission to reload the page:

const form = document.querySelector('form')
form.addEventListener('submit', event => {
  // submit event detected
  event.preventDefault()
})

At this point, clicking the "Submit Event" button in the form will not perform any action, except to provide us with controls.

Handling input element events

We can listen to many events in form elements

  • inputTriggered on the form element when the element value is changed
  • changeTriggered on the form element when the element value changes. In the case of textinputElement andtextarea, When the element loses focus, it will only be triggered once (not applicable to every single character typed)
  • cutTriggered when the user cuts text from a form element
  • copyTriggered when the user copies text from a form element
  • pasteTriggered when the user pastes text into a form element
  • focusTriggered when a form element gains focus
  • blurTriggered when the form element loses focus

This is a sample form demonstration on Codepen:

Look at the penForm event demoBy Flavio Copes (@flaviocopes) InCipher pen.

Tech Wiki Online!