HTML Form Tag Attributes – Best Practices

coding-standardshtmljavascriptstandardizationstandards

Checkout this HTML using the attribute action, method and target from <form></form> tag:

<form action="/action_page.php" method="get" target="_blank">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"><br><br>
  <button type="submit"></button>
</form>

Is a good practice using form tag's atributes in HTML? It will redirect the user to another page. Isn't a better option always using XHR Requests?

JavaScript XHR example in JQuery with previous HTML code:

  $("button").click(function(e){
    e.preventDefault();

    $.post("demo_test_post.asp",
    {
      name: $("[name='fname']")
    },
    function(data,status){
    });
  });

Best Answer

It's a technique that is used to allow websites to degrade gracefully if for some reason a browser doesn't have JavaScript turned on, or it is incompatible and the JavaScript engine crashes.

These days, between React, Angular, and several other frameworks that help build up the UI from formatted API calls (i.e. JSON, XML, etc.) and the world coming together around real web standards, the need to degrade gracefully is less important.

I will say that if there is no effective difference to the way the normal form action tag works, all you are doing is adding complexity for no gain. If you are packing that into a JSON object to POST or PUT to an API, then the JavaScript is necessary.

The example you posted is much more concisely and clearly covered by the stock behavior of the HTML elements. The JavaScript there isn't really performing any value, unless you are also going to perform validation and error handling without leaving the page.

Related Topic