DEV Community

David Hölkeskamp
David Hölkeskamp

Posted on

Today I Learned - form

TIL - form

12.07.2019

I had the requirement to create a page where there is a form displayed and the form buttons where placed inside a header, the template was something like this

<body>
  <header>
    Headline

    <!-- SUBMIT button should be displayed here -->

  </header>
  <main>
    <form>
      <label for="someinput">Some Label</label>
      <input type="text" id="someinput" name="someinput" />
    </form>
  </main>
</body>
Enter fullscreen mode Exit fullscreen mode

There are several ways to solve this:

  • Using CSS
    • everybody loves playing around with position: absolute and all it's children like top, left … - I know I do /s
  • Adding the header to the form

    • This could be a solution but in my case I was building a vue app and the header id a reusable component, whereas the form is displayed inside a
  • Using a cool attribute this article is all about

    • Using a builtin attribute could solve this problem (and in my case did)

Welcome form

The form attribute can be used to point an element to its parent form without beeing inside of it

<body>
  <header>
    Headline

    <button type="submit" form="myform">Submit</button>
  </header>
  <main>
    <form id="myform" action="myAction.php">
      <label for="someinput">Some Label</label>
      <input type="text" id="someinput" name="someinput" />
    </form>
  </main>
</body>
Enter fullscreen mode Exit fullscreen mode

The form you'll want to bind your button to needs to have an id - thats it. In your control, in my example the submit button, the attrribute form should point to the id of your form element.

The form attribute can be used on a variety of elements and is not limited to buttons.

Sources

Top comments (0)