Efficiency of reset html x reset javascript

1

I was creating a button to clear form, and I came across the function of HTML type='reset' but I was accustomed to using JavaScript for this to occur. So I wanted to ask for help to understand 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><scriptsrc="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>
    
asked by anonymous 21.11.2017 / 13:57

2 answers

1

The basic difference, which was already said by @Evandro Mendes, is that one is native and another is personalized. That is, via JavaScript you can manipulate the form any way you want.

On the other hand, it is important to note that resetting HTML is not the same thing as cleaning the form.

The reset is intended to leave the form to the source state 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 space 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 see that nothing will happen.

However, if you change some value, then resetting the form will return to its 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 perform the HTML change via JavaScript, removing the name , checked , selected , or textarea attributes, the native form reset will no longer be able to retrieve all values from HTML, 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><formmethod="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 notice that the use of .val() will behave differently from the use of .removeAttr() , which changes and removes the default HTML value. The .val() , on the other hand, is similar to the value insertion process by the user.

    
21.11.2017 / 14:58
1

Dear Victor,

In this case the question is not performance but functionality and practicality the input reset of the html is more practical but with Js can customize in question of performance actually being in html is better "faster" since it does not need to call a function but in UX issue is too bad for such a button, think if the user clicks "unintentionally"

    
21.11.2017 / 14:29