jQuery中防止表單提交兩次的方法
阿新 • • 發佈:2019-01-04
遇到過表單提交兩次的情況,做個記錄;
解決場景:首先是表單驗證,其次是防止多次提交表單;
jQuery中外掛:validate_submitHandler_plugin,具體的可以使用關鍵字搜尋;
使用方法:首先在前端定義form表單,然後jQuery來處理驗證和提交:
<form id="application-form" class="form-horizontal"> <div class="rds panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">源表資訊</h3> </div> <div class="panel-body"> <div class="form-group"> <label for="source-cluster"class="col-sm-2 control-label"><span class="required-field">*</span> 源叢集:</label> <div class="col-sm-8 control-section"> <input id="source-cluster" name="sourceCluster" class="form-control" value="${cluster.name}"readonly> </div> </div> <div class="form-group"> <label for="source-schema" class="col-sm-2 control-label"><span class="required-field">*</span> 源資料庫:</label> <div class="col-sm-8 control-section"> <select id="source-schema" name="sourceSchema" class="form-control"></select> </div> </div> </div> </div> <div class="rds panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">目標表資訊</h3> </div> <div class="panel-body"> <div class="form-group"> <label for="target-cluster" class="col-sm-2 control-label"><span class="required-field">*</span> 目標叢集:</label> <div class="col-sm-8 control-section"> <select id="target-cluster" name="targetCluster" class="form-control"></select> </div> </div> <div class="form-group"> <label for="target-schema" class="col-sm-2 control-label"><span class="required-field">*</span> 目標資料庫:</label> <div class="col-sm-8 control-section"> <input type="text" id="target-schema" name="targetSchema" class="form-control" placeholder="database number"> </div> </div> </div> </div> <button id="btn-submit" type="submit" class="btn btn-primary" disabled>提交</button> </form>
$("#application-form").validate({ rules: { sourceCluster: "required", sourceSchema: "required", targetCluster: "required", targetSchema: "required", }, submitHandler: function() { const sourceCluster = $("#cluster-name").val(); const sourceDatabase = $("#source-schema").selectpicker("val"); const targetCluster = $("#target-cluster").selectpicker("val"); const targetDatabase = $("#target-schema").val(); handleSubmit({sourceCluster, sourceDatabase, targetCluster, targetDatabase}); } });
其中會遇到的問題,可以參考我在Stack Overflow上的回答:
https://stackoverflow.com/questions/23693658/jquery-validate-submits-form-twice