Reset in input fields after submit with Jquery

10

By sending the input field values through JQuery to a PHP page I can do the action without refreshing the main page, but I can not make the input fields "empty" again?!? How do I then apply the "reset" after submission?

HTML:

<div id='status'></div>
<form id="new_user" method="post" action="javascript:func()">
    <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='enviar'/>
    <br />
</form>

CSS:

#status{
    position:absolute;
    width: 150px;
    height: 30px;
    top: 150px;
    left:10px;
    border: 1px solid black;
    color: red;
}

JQuery:

$(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='Enviando'/></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("");
        }
    });
  });
});

jsfiddle

    
asked by anonymous 04.07.2014 / 16:44

4 answers

14

Clearing all fields on a form:

 
$(':input','#form')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Resetting the initial values of a form:

$('#form')[0].reset();

Now just choose one of the solutions and add after your $.post() .

JSFiddle Example

04.07.2014 / 17:13
3

Complementing the previous response to leave the generic function using only javascript, it follows the code that works for other input types.

var elements = document.getElementsByTagName("input");
for (var i=0; i < elements.length; i++) {
    if (elements[i].type == "text") {
        elements[i].value = "";
    } 
    else if (elements[i].type == "radio"){
        elements[i].checked = false;  
    }
    else if (elements[i].type == "checkbox"){
        elements[i].checked = false;
    }
    else if (elements[i].type == "select") {
        elements[i].selectedIndex = 0;
    } 
}
    
12.01.2015 / 17:18
0

Use the following:

var elements = document.getElementsByTagName("input");
for (var i=0; i < elements.length; i++) {
  if (elements[i].type == "text") {
    elements[i].value = "";
  }
}
    
04.07.2014 / 16:48
0

You can use the native method of reset() JavaScript to reset the entire form to its default state.

Example:

$("#myForm')[0].reset();

Note: This can not reset certain fields, such as type="hidden".

The same thing can be done using trigger jQuery() :

$("#myForm').trigger("reset");

try to search a little in stackoverflow, there are several topics approaching it

Reset Form

    
12.01.2015 / 17:27