The Web Dev Guide by Wishtack
  • The Web Dev Guide by Wishtack
  • HTML
    • HTML Tags
    • HTML Attributes
    • Content Formatting
    • Empty Tags vs Content Tags
    • Some Links
  • ECMAScript
    • Some History
    • Language Properties
    • Single-Threaded thus Asynchronous
    • The Event Loop
    • Classes
    • Hoisting is Dead: var vs. let vs. const
    • this & "binding"
    • Arrow Functions
    • Template Strings
    • Syntactic Sugar
      • Spread
      • Destructuring
      • Rest
      • Object Literal Property Value Shorthand
    • Named Parameters
    • Compatibility
  • Tools
    • Node.js
    • NPM
    • Yarn
    • Webpack
    • WebStorm
    • StackBlitz
  • DOM
    • What Is It?
    • Element Selection
    • Element Modification
    • Events
  • Forms
    • The <form> tag
    • Form elements
    • Form validation
  • Networking
    • Fetch Web API
  • CSS
    • Selectors
    • Transforms
    • Transitions
    • Animations
    • Web Animations API
    • Sass
  • Responsive Web Design
    • Viewport
    • Media Queries
    • Grid Layout
    • Flex Layout
    • Frameworks & Libraries
  • Web APIs
  • Testing
    • Unit Testing
    • End to End Testing
  • Security
    • Injection
    • DOM XSS
    • Insecure Direct Object Reference
    • Cross-Site Request Forgery
    • Client vs API Validation
    • API Unauthorized Access and Data Leak
  • More Links
Powered by GitBook
On this page
  • <form> tag attributes
  • Example
  • Intercepting submit event
  1. Forms

The <form> tag

<form> tag attributes

The first step when implementing an HTML form is to add a form tag.

<form>
...
</form>

The form tag has three main attributes:

  • action: that describes the URL where the data should be sent when the form is submitted.

  • enctype: that specifies the encoding to use for sending data (application/x-www-form-urlencoded, multipart/form-data and text/plain).

  • method: that controls the HTTP method that will be used to send data to server.

Example

<form
    method="post"
    enctype="application/x-www-form-urlencoded"
    action="https://mylibrary.io/books">
</form>

Intercepting submit event

In most cases in a JavaScript application, the content shouldn't be sent directly over the network to the backend but it should be intercepted by the JavaScript on submission.

When the user submits the form (e.g.: presses enter or clicks on a <button type="submit"> inside the form), the form element triggers a submit event.

The JavaScript can be intercepted by adding an event listener and the default behavior (sending the form's data to the backend) disabled calling the preventDefault method on the event.

const form = document.querySelector('form');

form.addEventListener('submit', submitEvent => {
    submitEvent.preventDefault();
    ...
});

PreviousFormsNextForm elements

Last updated 6 years ago