How to Create HTML Forms Properly: Semantics.

Forms are the most important part of any web application. Without the form, we wouldn’t have sites like Google, Facebook, Amazon, Reddit, etc. However, the more I browse the web, the more I see poor implementation of the forms.

In this series, we’ll take a look at the steps involved in creating a form for the web, how to think about the code we’ve written, and the ideas along the way. The series is divided into the following sections:

It makes the most sense to start with the right words because, as we will see through the series, semantics will play its part in every other part. This is probably the starting point when you start coding. So let’s get started.

Start with a form.

First and foremost, whenever we are dealing with some kind of user input, we should start with a. <form> Tag. Some people who work with JavaScript may choose to skip it. <form> Tag because form submission can be handled with AJAX application. However, this is an error (not the AJAX part, but the omission). <form> Tag).

Of <form> Tag Important for accessible reasons. Some screen readers have a special mode for forms that is activated only when a. <form> Tag.

including. <form> The tag also ensures our shape. Can be submitted even if JavaScript is not enabled.. You just want to make sure the form is included. action The attribute knows where to send the data. Hooray, progressive rise!

To this, you might reply, “But Austin, I’m building an SPA. So even if the user sees the form, it means JavaScript has to be enabled. And you’re right. Although, If this is a critical format, you may want to consider supporting a non-JS world. The day may come when you want to implement SSR. ۔

If you are a JavaScript developer and you are still not convinced by the previous points, consider the following code. See how to use a. <form> Makes our job easier. Using the form submission event, we can access the form node, which makes sending data much easier. FormData.

const form = document.querySelector("#your-form")
const url = "https://jsonplaceholder.typicode.com/posts"

form.addEventListener('submit', e => {
  e.preventDefault()

  const data = new FormData(e.target)
 
  fetch(url, {
    method: 'POST',
    body: new URLSearchParams(data)
  })
})

(Note that you can send the form data directly as the body of the application, but this will set the HTTP header. multipart/form-data, Which is usually not what I want).

One also has to consider the user experience to use. <form> Tag. Have you ever filled in an input, pressed the “Enter” key, and submitted the form magically even though you didn’t click the submit button (e.g., Dick Dickgo Search)? Because this beautiful user experience is possible <form> The tag is there

(I guess you can use JavaScript to find each input in a form and add one. keydown Event listener for the “Enter” key, but just a is not easy to use. <form>?)

Finally , <form> The tag has no visual features. So I can’t think of any good reason to give it up. Less code, maybe? But the benefits of using it far outweigh the costs.

Use correct input.

It is important to use the correct input types when creating the form. Of course, a <div> Styling is easy in many cases, but here’s a lot that is baked into local shape elements that you’ll have to recreate:

  • Accessible via keyboard navigation with tab Key
  • Focused
  • Access to client-side authentication.
  • Keyboard dialog to select radio آدانوں
  • Keyboard interaction to check. checkboxes آدانوں
  • Keyboard dialog to select select authorities
  • Submit additional forms
  • Explanatory words for screen readers.

Try to do all this with A. <div> And you’ll probably fail miserably and quit web development. Please don’t do that.

Instead, you should be able to find appropriate input on anything you can think of. After all, according to MDN, there are 22 different types of exchanges, as well. <select> And <textarea>.

Need some help?

  • Is there a choice of input options?
    • Yes: Are there more than 6 options available?
      • Yes: Can multiple options be selected?
        • Yes: Use a. <select> with the multiple Description
        • No: Use a. <select>
      • No: Can multiple options be selected?
        • Yes: use multiple. <input type="checkbox">
        • No: Use multiple. <input type="radio"> With the same name Description
    • No: Is this a long piece of text?
      • Yes: Use a. <textarea> Element
      • No: Is the input appropriate? type?
        • Yes: Use the appropriate input type.
        • No: Use normal. <input>

At this point, you might be saying, “Yeah, it’s all right and dirty. In fact, I already knew about all the different input types. But I was given a design with super fancy inputs that was available.” Doesn’t look like any of the inputs. Well, hard. For a long time, we had to choose between custom-designed forms or semantic forms.

This is no longer the case, and we now have enough flexibility for form design. We’ll take a closer look at this later, but for now, just trust me. Start developing with a solid, semantic foundation and put custom designs on top.

One last thing I want to mention is that whenever you have multiple inputs that are relevant, they should be wrapped together. <fieldset> Tag. An example might be two fields in which the first name and the last name are asked.

Highly relevant use case for. <fieldset> Radio or checkbox for input. They are almost always grouped together. Each of the inputs has a label, and the group itself needs a “label”, but when working with a. <fieldset>, We use <legend> Tag.

Each input gets a name and a label.

Of name An attribute is required for any form input to send identification data to a server. By default, this is what is used as the key for the query a GET Request, or I. body One of POST Request You will think that it is clear that we need it.

However, with the increasing landscape of the JavaScript framework, it has become much easier to omit this attribute and bind some data objects to some input. For example, in Vue:

<template>
  <form @submit="onSubmit">
    <input v-model="dataKey">
  </form>
</template>

<script>
  export default {
    data: () => ({
      dataKey: ''
    }),
    methods: {
      onSubmit() {
        console.log(this.dataKey)
      }
    }
  }
</script>

This will work well in most cases, but as we mentioned above, it is a good idea to keep progress in mind. If this form was presented on the server and JavaScript is disabled in the browser, the form will not work. Even if we add forms. action, We will only send data without any kind of identifier.

For the non-JS world, getting out is more important than accounting. name The attribute can actually have a negative user experience. We will see in more detail in the next article.

Moving to labels

I think this topic has been lengthened, but I repeat here. Each form input requires a label, Always.

No placeholder.

No title.

A label

You have 3 options to work with:

  • Input wrapping label: <label>Name: <input name="name"></label>
  • Label with for Description: <label for="name">Name:</label><input name="name">
  • aria-label: Name: <input name="name" aria-label="Name">

There is no significant difference between the first two, to the best of my knowledge, except the need for a. for Attribute on label, and one. id For this reason alone, I prefer to use option 1.

Update (04/07/2020): reader. Kate Kalsevich. He pointed out to me that there is a difference in reality. label (Wrapping input) and a clear. label Using (a) for Description). The short version is that clear labels are more accessible. More details in the next article.

Now let’s look at the third option, aria-label. aria-labels are very useful for adding context labels to elements without adding visual labels. This is great for accessible inputs (for screen readers) without showing labels (or labels that look like placeholders).

We will consider labels further in the Accessible section, but for now I will say that my favorite way to add labels is the first option.

Add submission button.

For a while, I wondered if the submission button was always needed on a form. In many cases, this is not clear from the design we need. For example, take the following design:

Sexy search form, bro. Who needs to submit a button?

There are some issues with dropping the submission button:

  • It is not clear that the user has to press the “Enter” key to submit (especially for screen reader users).
  • This is not valid HTML.
  • You may not find Submission (‘Oh’)

Submission is a feature of a browser that you may have tried before. If you select a text input and press the “Enter” key, the form will be submitted. This behavior is described in HTML Spec.

“If the user agent supports the user to submit the form (for example, on some platforms he submits the form by pressing the” Submit “key while focusing on the text field) Activation behavior Due to the user’s agent can run artificial click activation steps on this default button.

HTML details

“If the form does not have a submit button, if the form has more than one field that prevents sub-submission, the form submission procedure should do nothing, and the form element itself Should be submitted.

For the purpose of the previous paragraph, an element is a field that prevents the addition of a form element if it is an input element whose form is the form element and whose type attribute is in one of the following : Text, search, url, telephone, email, password, date and time, date, month, week, time, local date and time, number “

HTML details

In other words (and it depends on the implementation of the browser), pressing the “Enter” key while focusing on text input will ignite the fire. click Event on the form submission button. Many browsers still implement additional requests even if the submission button is missing, but I think it is better to add the button anyway.

Here are two ways to write a submit button in HTML:

  • <input type="submit" value="Submit this form">
  • <button type="submit">Submit this form</button>

I prefer <button type="submit">.

Note that if you type Inside a button attribute <form> The tag will assume it’s one. submit Clicking on the button will result in the submission of the form.

I try to get in the habit of arranging clearly. type In the form of any button, because in some rare cases, I actually want the type of button. button, To do something other than submit (such as one click to copy). Therefore, it is not always necessary to include. type Attribute, but I think it’s a good habit.

Oh yes, and with regard to the inclusion of the submission button for the design of the above example, we will consider later in the article to visually hide things like the submission button.

Concluding remarks.

An example form following the methods we’ve covered might look like this:

<form>
  <fieldset>
    <legend>Operating System</legend>
    <label>
      <input type="radio" name="os" value="windows">
      Windows
    </label>
    <label>
      <input type="radio" name="os" value="mac">
      Mac
    </label>
    <label>
      <input type="radio" name="os" value="linux">
      Linux
    </label>
  </fieldset>

  <fieldset>
    <legend>Favorite JS Frameworks</legend>
    <label>
      <input type="checkbox" name="ck-angular" value="angular">
      Angular
    </label>
    <label>
      <input type="checkbox" name="ck-react" value="react">
      React
    </label>
    <label>
      <input type="checkbox" name="ck-vue" value="vue">
      Vue
    </label>
    <label>
      <input type="checkbox" name="ck-svelte" value="svelte">
      Svelte
    </label>
  </fieldset>

  <label>
    Position
    <select name="position">
      <option value="" selected></option>
      <option value="fs">Full Stack</option>
      <option value="fe">Front End</option>
      <option value="be">Back End</option>
      <option value="de">Designer</option>
      <option value="pm">Project Manager</option>
      <option value="ceo">CEO</option>
    </select>
  </label>

  <label>
    Years of Experience
    <input name="exp" type="number">
  </label>

  <fieldset>
    <label>
      First Name
      <input name="fname">
    </label>
    <label>
      Last Name
      <input name="lname">
    </label>
  </fieldset>  

  <label>
    Email
    <input name="email" type="email">
  </label>

  <label>
    Comments
    <textarea name="comments"></textarea>
  </label>

  <button type="submit">Submit</button>
</form>

We went into depth on a number of topics that might otherwise seem superficial. However, the important advice boils down to this: always use. <form> Tag, use right. input Type, wrap each input in a label, and add a submit button.

I hope it wasn’t boring, and hey, maybe you’ve learned something new. My goal was to encourage you to think critically about the things you are creating and use the tools that the platform is already providing for us. Start with words and build from there.

Please tell, whats the story of them big puppys ………..

Thanks so much for reading. If you liked this article, please share it, and if you want to know when I publish more articles, sign up for my newsletter or Follow me on Twitter. Very good!

.

Leave a Reply

Your email address will not be published.