Logo

dev-resources.site

for different kinds of informations.

Web Apps from scratch: Forms

Published at
5/2/2021
Categories
html
javascript
webdev
vanilla
Author
snickdx
Categories
4 categories in total
html
open
javascript
open
webdev
open
vanilla
open
Author
7 person written this
snickdx
open
Web Apps from scratch: Forms

Getting into form ☑

Forms are a fundamental component of web applications. They allow us to validate and take input from users which become structured data in our databases. This post will go through some of the basics of forms.

The Form element & attributes

The form element is created with the form tab and has the following attributes:

  • autocomplete: can disable the browser's autocomplete, values "on" or "off"
  • method: specified the HTTP method, values "GET" or "POST"
  • enctype: affects the MIME Type of the data submitted. Values:
    • application/x-www-firn-urlencoded
    • text.plain
    • mutlitpart/form-data

Form input elements

It's important to use the appropriate input elements for the data needed. Some elements have a dedicated tag while others are attributes on the input tag.

  • Selecting a single value from a list
    • input[type="radio"]
    • select
    • datalist
  • Selecting multiple values from a list
    • select (with "multiple" attribute)
    • input[type="checkbox"] multiple boxes with the same name
  • Boolean Values: single checkbox
  • Time : input[type= "week|time|datetime|date|week|month|datetime-local"]
  • Numeric
    • input[type="text" inputmode="numeric|decimal"]
    • input[type="number"]
    • input[type="range"], gives a slider (best used for small ranges)
    • Files : input[type="file"]
    • password : input[type="password"]
  • Email : input[type="email"]
  • Telephone : input[type="telephone"]
  • URL : input[type="URL"]

Form validation

We can add simple validation to our forms to prevent them from submitting unless certain conditions are met.

This is done via validation attributes such as:

  • required: field must contain a value
  • minlength: specifies the minimum length of valid input
  • pattern: field must match with the specified Regular Expression.

Inputs with type=email/url/telephone will also validate input appropriately.

Form Submission

By default, an HTML form element will make a GET request to the current URL and append the form data as a query string.

For Example the following form:

<form id="myform">
     <input type="text" name="username"/>
     <input type="password" name="password"/>
     <submit>Send</submit>
</form>
Enter fullscreen mode Exit fullscreen mode

Would redirect the browser to /?username=bob&password=pass when the form is submitted with the values 'bob' and 'pass'. Normally there would be code on the backend that will receive the data from the URL.

We can override these defaults with the method and action attributes mentioned earlier.

Alternatively, for single-page applications we can use javascript to prevent the page redirect and submit the form.

document
  .querySelector('#myform')
  .onsubmit = async function(event){
      event.preventDefault();//prevent the form submission
      const formData = new FormData(event.target);
      //pull out all the data from the form
      const data = Object.fromEntries(formData.entries());
      const response = await fetch(
         '/myserver', 
         { 
           method:'POST', 
           body:JSON.stringify(data)},
           headers: { 'Content-Type': 'application/json'}
         }
      );//send data to the server
      const text = await reponse.text;
      alert(text); //alerts the server's reponse
}
Enter fullscreen mode Exit fullscreen mode

The snippet above prevents the page redirect and sends the form data as JSON to the URL provided.

Going Deeper

You can see a more in-depth example at this
Repl that will allow you to change the content types and see the response from the server.

Conclusion

This concludes the basics of HTML forms as you can see, there's much you can accomplish with standard HTML and Javascript.

vanilla Article's
30 articles in total
Favicon
🎨🛠️ 𝗩𝗮𝗻𝗶𝗹𝗹𝗮 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 𝘁𝗼 𝗘𝗺𝗽𝗼𝘄𝗲𝗿 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 🚀🌐
Favicon
Mastering Vanilla JavaScript and Libraries: The Road to Dynamic DOM Rendering
Favicon
🌟 Vanilla Update: New Components and Enhanced Features! 🌟
Favicon
🌐 Unlock Development with Vanilla: The Non-Framework Powerhouse 🌐
Favicon
🚀 Vanilla & CSSer Major Update! 🚀
Favicon
How to upload files to a server in NodeJS with Formidable
Favicon
🚀 Vanilla Update: A New Development Methodology! 🚀
Favicon
Secure Text Encryption and Decryption with Vanilla JavaScript
Favicon
🚀 Vanilla Framework Update: Meet CSSer! 🚀
Favicon
🌟 Vanilla & CSSer Accessibility Update! 🌟
Favicon
Storing and retrieving JavaScript objects in localStorage
Favicon
New lightbox package here!
Favicon
Data-driven UIs
Favicon
A11y: Vanilla javascript aria-live announcer
Favicon
Keyboard input in Node.js
Favicon
Javascript Made Simple!
Favicon
Array methods and when to use them, forEach, map, reduce
Favicon
Which should you use? Array.from vs. Spread Operator
Favicon
Tiny Vanilla.js Projects
Favicon
Maneras de clonar un objecto en javascript
Favicon
Vanilla JavaScript data fetch
Favicon
Vanilla(ts) configuration with Webpack. a little bit different.
Favicon
My first Chrome Extension
Favicon
Speedy Typer Game
Favicon
What is CSS @scope and why should I care?
Favicon
Path aliases with Vanilla Node JS
Favicon
Montar SPA de cero con Vanilla y Jest
Favicon
Web Apps from scratch: Forms
Favicon
Sending asynchronous POST requests with pure JS: ditching jQuery's ajax
Favicon
State Management with Vanilla JavaScript

Featured ones: