我有一个带有多个选项卡/表单的应用程序,将被提交。与其为每个表单提供单独的提交功能,我不希望设计一个动态函数来提交带有submitFrm
类的任何表单。这是我当前代码的示例:
$('.frmSubmit').on('submit', submitFrm);
function submitFrm(e) {
e.preventDefault(); // Prevnts default form submit.
var frmID = $(this).prop("id"),
formData = $('#' + frmID).serialize(), //or this way $(this).serialize()
submitBtn = $(this).find(':submit');
if (formData) {
$('#' + frmID).find(':submit').prop('disabled', true); // Disable submit button
// or this submitBtn.prop('disabled', true);
/*
Here is AJAX call.
*/
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frmTab1" id="frmTab1" class="frmSubmit" autocomplete="off">
<div class="form-group">
<label class="control-label" for="activ"><span class="label label-primary">Active:</span></label>
<select class="form-control" name="frmTab1_active" id="frmTab1_active" required>
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="code"><span class="label label-primary">Code:</span></label>
<input type="text" class="form-control" name="frmTab1_code" id="frmTab1_code" maxlength="4" required>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="submit" name="frmTab1_submit" id="frmTab1_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div id="message" class="alert message-submit"></div>
</div>
</div>
</form>
我正在辩论我应该对$(this)
,find()
表单数据使用serialize()
对象还是应该使用表单ID?有什么区别吗?我也想知道我是否使用多种表单中的此功能提交数据是好的做法?如果有人有任何建议,请告诉我。
答案 0 :(得分:0)
您可以像这样简单地使用$(this).serialize()
:
$('.frmSubmit').on('submit', submitFrm);
function submitFrm(e) {
e.preventDefault();
var formData = $(this).serialize();
var submitBtn = $(this).find(':submit');
if (formData) {
submitBtn.prop('disabled', true);
}
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frmTab1" id="frmTab1" class="frmSubmit" autocomplete="off">
<div class="form-group">
<label class="control-label" for="activ"><span class="label label-primary">Active:</span></label>
<select class="form-control" name="frmTab1_active" id="frmTab1_active" required>
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="code"><span class="label label-primary">Code:</span></label>
<input type="text" class="form-control" name="frmTab1_code" id="frmTab1_code" maxlength="4" required>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<button type="submit" name="frmTab1_submit" id="frmTab1_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div id="message" class="alert message-submit"></div>
</div>
</div>
</form>