Reset html x reset javascript efficiency

Asked

Viewed 521 times

1

I was creating a button to clear form, and I came across the function of HTML type='reset' but I was used to using Javascript for this to occur. Therefore wanted to ask for help to understand what the difference in efficiency from one to another.

Example of reset in HTML

<form method="POST" action="">
    <br>
        <div class="col-lg-12">
            <div class="col-lg-4"><!-- Inicio Input Código -->
                <label for="ex1">Codigo: </label>
                <input  type="text" class="form-control" id="codigo" codigo="codigo" size="60"><br>
            </div><!-- FimInput Código -->
        </div>

        <div class="col-lg-12">
            <div class="col-lg-4"><!-- Inicio Input Usuário -->
                <label for="ex1">Usuário: </label>
                <input  type="text"  class="form-control" id="usuario" codigo="usuario" size="40"><br>
            </div><!-- Fim Input Usuário -->

            <div class="col-lg-8"><!-- Inicio Input Senha Antiga -->
                <label for="ex1">Senha Aniga: </label>
                <input  type="text"  class="form-control" id="senha" codigo="senha_antiga" size="40"><br>
            </div><!-- Fim Input Senha Antiga -->
        </div>

    <input type="reset" value='Limpar Tela'>

</form><!-- Fim do formulario -->

Example of reset in Javascript

$(function($) {
  // Quando o formulário for enviado, essa função é chamada
  $("#new_user").submit(function() {
    // Colocamos os valores de cada campo em uma váriavel para facilitar a manipulação
      
    var name = $("#name").val();
    var mail = $("#mail").val();
    var password = $("#password").val();
    // Exibe mensagem de carregamento
    $("#status").html("<center><img src='core/img/loader.gif' alt='Enviado'/></center>");
    // Fazemos a requisão ajax com o arquivo envia.php e enviamos os valores de cada campo através do método POST
    $.post('#', {name: name, mail: mail, password: password }, function(resposta) {
        // Quando terminada a requisição
        // Exibe a div status
        $("#status").slideDown();
        // Se a resposta é um erro
        if (resposta != false) {
          // Exibe o erro na div
          $("#status").html(resposta);
        } 
        // Se resposta for false, ou seja, não ocorreu nenhum erro
        else {
          // Exibe mensagem de sucesso
          $("#status").html("<center>Cadastro realizado com sucesso!</center>");
          // Limpando todos os campos
          $("#name").val("");
          $("#mail").val("");
          $("#password").val("");
        }
    });
      
      //limpar form
      $(':input',this)
          .not(':button, :submit, :reset, :hidden')
          .val('')
          .removeAttr('checked')
          .removeAttr('selected');
      //this.reset();
  });
});
#status{
    position:absolute;
    width: 150px;
    height: 30px;
    top: 150px;
    left:10px;
    border: 1px solid black;
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id='status'></div>
<form id="new_user" method="post" action="javascript:;">
    <input type='text' name='name' id='name'/>
    <br />
    <input type='text' name='mail' id='mail'/>
    <br /><input type='password' name='password' id='password'/>
    <br /><input type='submit' name='submit' id='submit' value='Limpar Tela'/>
    <br />
</form>

2 answers

1

Dear Victor,

In this case the issue is not performance, but functionality and practicality the html reset input is more practical but with Js you can customize in terms of performance actually being in html is better "faster" because it does not need to call a Function but in the matter of UX is very bad for a button like this, think if the user clicks "unintentionally"

  • Yeah, I’m thinking about it, too

1


The basic difference, which has already been told by @Evandro Mendes, is that one is native and another is personalized. That is, via Javascript you can handle the form the way you want.

On the other hand, it is necessary to understand that the HTML reset is not the same thing as cleaning the form.

The reset aims to leave the form to the state of origin of its values:

As you can see in the form below, there are some pre-selected values, such as name, email, some programming languages and a free area for text (with text inside, without placeholder).

<form method="post" action="#">
  <fieldset>
    <legend>Dados cadastrais</legend>

    <label for="name">Nome:</label>
    <input id="name" name="name" value="Gabriel Heming" />

    <label for="email">E-mail:</label>
    <input id="email" name="email" value="[email protected]" />
  </fieldset>
  
  <fieldset>
    <legend>Linguagens de programação</legend>
    <label for="php">PHP:</label>
    <input type="checkbox" id="php" name="languages[]" value="PHP" checked="checked" />
    
    <label for="JavaScript">JavaScript:</label>
    <input type="checkbox" id="JavaScript" name="languages[]" value="JavaScript" checked="checked" />
    
    <label for="C#">C#:</label>
    <input type="checkbox" id="C#" name="languages[]" value="C#" />
    
    <label for="java">Java:</label>
    <input type="checkbox" id="java" name="languages[]" value="Java" />
  </fieldset>  


  <fieldset>
    <legend>Texto livre</legend>
    <textarea id="textarea" name="textarea">Área para texto livre</textarea>
  </fieldset>
  
  <fieldset>
     <button type="reset">Reset HTML</button>
  </fieldset>
</form>

If you perform the reset, you will find that absolutely nothing will occur.

However, if you change some value and then reset the form back to the original values. This is quite common in registration update forms, where a form is already filled with default values.

On the other hand, if you make the HTML change via Javascript, removing the attributes name, checked, selected or the content of a textarea, native form reset will no longer be able to recover all HTML values, because what it does is just reload what is saved in HTML.

$(document).ready(function() {
      $('#reset').click(function() {
        $(':input')
            .not(':button, :submit, :reset, :hidden')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');
        
        // apenas como exemplo, o resultado de removeAttr é diferente do uso de .val();
        $('#email').removeAttr('value');
      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
      <fieldset>
        <legend>Dados cadastrais</legend>

        <label for="name">Nome:</label>
        <input id="name" name="name" value="Gabriel Heming" />

        <label for="email">E-mail:</label>
        <input id="email" name="email" value="[email protected]" />
      </fieldset>
      
      <fieldset> 
        <legend>Linguagens de programação</legend>
        <label for="php">PHP:</label>
        <input type="checkbox" id="php" name="languages[]" value="PHP" checked="checked" />
        
        <label for="JavaScript">JavaScript:</label>
        <input type="checkbox" id="JavaScript" name="languages[]" value="JavaScript" checked="checked" />
        
        <label for="C#">C#:</label>
        <input type="checkbox" id="C#" name="languages[]" value="C#" />
        
        <label for="java">Java:</label>
        <input type="checkbox" id="java" name="languages[]" value="Java" />
      </fieldset>  

      <fieldset>
        <legend>Texto livre</legend>
        <textarea id="textarea" name="textarea">Área para texto livre</textarea>
      </fieldset>
      
      <fieldset>
        <button type="reset">Reset HTML</button>
        <button type="button" id="reset">Reset JavaScript</button>
      </fieldset>
    </form>

You may note that the use of .val() will behave differently from the use of .removeAttr(), which changes and removes the default HTML value. O .val(), on the other hand, it is similar to the process of inserting the value by the user.

  • thanks for the @Gabrielherning clarification, so as I am creating a form that receives many queries, data insertion and etc... I believe that the most correct to do to fully clean is the same Javascript right

  • @Victor is not right or wrong, it is only one of the possibilities. The most important thing is that it solves your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.