0

I would like to clear the inputs after the user submit the form using ajax.

My code works fine, i made based tutorials and after send fields are still with values. I want to clean them.

<script type="text/javascript">
$(document).ready(function(){

$("#inserir").click(function(){
    $('#loadingDiv')
        .hide()  
        .ajaxStart(function() {
            $(this).show();
        })
        .ajaxStop(function() {
            $(this).hide();
        })
    ;
var nome=$("#nome").val();
var email=$("#email").val();
var confirmacao=$("#confirmacao").val();
var acompanhantes=$("#acompanhantes").val();
// loading image
$("#message").html('<center><img src="images/ajax.gif" /></center>');

$.post('inserir.php', {nome: nome, email: email, confirmacao: confirmacao, acompanhantes: acompanhantes},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500); 
});
return false;
});
});
</script>

Php

 $nome = $_POST['nome'];
 $email = $_POST['email'];
 $confirmacao = $_POST['confirmacao'];
 $acompanhantes = $_POST['acompanhantes'];
//Insert Data into mysql
$query=mysql_query("INSERT INTO cadastro_rsvp(nome,email,confirmacao,acompanhantes,id) VALUES('$nome','$email','$confirmacao','$acompanhantes','')");
 mysql_close($con);

if($query){
echo "Dados enviados";
}
else{ echo "Erro!"; }
}
4

4 回答 4

2

这将清除所有文本框、文本区域、单选按钮、复选框值:将“ #myFormId ”替换为您的表单 ID。

$('input:text, input:password, input:file, select, textarea', '#myFormId').val('');
$('input:checkbox, input:radio', '#myFormId').removeAttr('checked').removeAttr('selected');

您必须在代码中的此行之后添加它:

$("#message").fadeIn(500); 
于 2013-11-13T17:09:17.930 回答
1

使用您的字段之一的示例:

$("#nome").val('');

上面的代码将基本上空白文本字段中的任何内容。

于 2013-11-13T17:02:17.697 回答
0

如果要在将字段保存到数据库清除字段,则必须在收到服务器响应success清除输入,在这种情况下,在$.post.

$.post('inserir.php',
  {nome: nome, email: email, confirmacao: confirmacao, acompanhantes: acompanhantes},
  function(data){
    $("#message").html(data);
    $("#message").hide();
    $("#message").fadeIn(500);
    //HERE YOU PERFORM THE RESET (I suppose that they are input text fields):
    $("#nome").val('');
    $("#email").val('');
    $("#confirmacao").val('');
    $("#acompanhantes").val('');
  });
  return false;
});

此外,查看jQuery.post 文档以获取更多信息以直接使用成功回调函数。

于 2013-11-13T17:20:51.860 回答
0

我使用 HTML 来做到这一点。

<button type="reset" value="Reset">Reset</button>
于 2013-11-13T17:06:51.347 回答