Reset to input fields after Ubmit with Jquery

Asked

Viewed 29,209 times

11

By sending input fields values via Jquery to a PHP page I can do the action without "refreshing" the main page but I can’t make input fields "empty" again?!? How to apply "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

5 answers

21


Clearing all fields of 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().

Example in Jsfiddle

  • Thank you friend. Your first example didn’t work with me?!? but the second one was perfect just one note: it stayed inside Isis. Thanks for the help :)

  • @Lauromoraes If you open the answer Jsfiddle it is working. You have not forgotten to change the form ID?

  • I switched yes...but I have no idea what pq didn’t work for me here. The second example (redefining initial values) worked perfectly. After the positive feedback of the data and the response. Again grateful for the help :)

  • How do you reset all page fields?

  • @Dr.G The second snippet of code shows how to reset a form. If you have multiple Forms on a page, reset them all instead of one. If you need more details, I suggest you ask a new question.

3

Complementing the previous answer to make the function more generic using javascript only, follow the code that works for other types of input.

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;
    } 
}

1

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

Example:

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

Note: This cannot reset certain fields, such as type = "Hidden".

Amesma thing can be performed using Trigger jQuery():

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

try searching a little in stackoverflow, there are several topics addressing the same

Reset Form

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 = "";
  }
}
  • It didn’t work here...and I have 3 fields, a password and two text

-1

Using Jquery

$('#form').each(function () { this.reset(); });

Browser other questions tagged

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