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

How to hide and show element before submit form using javascript?

本文关键字:隐藏 显示 元素 表单 何使用 javascript 提交      更新时间:2023-09-26

如何使用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>

我建议使用$.ajax()并使用beforeSend&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()
        }
    });
});

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

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

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

$("#myForm").submit(function() {
    $("#sub").hide();
    $("#loading").show();
    $.post(this.action, $(':input', this).serializeArray(), function(info){ 
        $("#result").html(info); 
    });
    clearInput();
    return false;
});