如何使用javascript在提交表单之前隐藏和显示元素?

时间:2014-11-13 15:19:34

标签: javascript jquery html

如何使用javascript在提交表单之前隐藏和显示元素?

当我按下按钮时,我想在提交表单前显示id="loading"并隐藏id="sub"

我测试了这段代码,我会显示id="loading"并隐藏id="sub"但不提交表单。

我该怎么做?

<form id="myForm" name="send_ask" action="xxx.php" method="post">
    <input type="text" name="id" value="12345" style=" display: none;">
    <button id="sub">Send</button>
    <span id="result"></span>
</form>
<div id="loading" style=" display: none;">WAIT</div>



<script type="text/javascript">
$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         $("#sub").hide(),
         $("#loading").show(),
         function(info){ $("#result").html(info); 
   });
 clearInput();
});

$("#myForm").submit( function() {
  return false; 
});


</script>

2 个答案:

答案 0 :(得分:0)

我建议使用$.ajax()并使用beforeSend&amp; complete。例如:

$('#myForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: $("#myForm").attr("action"),
        data: $("#myForm :input").serializeArray(),
        type: 'post',
        dataType: 'html',
        success: function(data){
            $("#result").html(data);
        },
        beforeSend: function(){
            $("#loading").show()
        },
        complete: function(data){
            $("#loading").hide()
        }
    });
});

答案 1 :(得分:0)

您的$.post参数错误。正确的是

$.post(url, data, function(result){.. run some code on complete .. }, dataType);

因此,您需要在完整回调中或在帖子之前运行show / hide逻辑。更好的方法是将处理程序附加到提交函数而不是按钮单击。

$("#myForm").submit(function() {

    $("#sub").hide();
    $("#loading").show();

    $.post(this.action, $(':input', this).serializeArray(), function(info){ 
        $("#result").html(info); 
    });

    clearInput();

    return false;

});