【发布时间】:2014-03-07 11:52:08
【问题描述】:
我有表单,它是使用$.ajax 函数提交的,但在提交之前我使用 jquery validate() 函数对其进行验证。但是当我点击提交按钮时,两个功能同时运行。那么,如何在提交之前验证表单。
HTML
<div class="panel-body">
<form class="form-horizontal" name="attr_val_form" id="attr_val_form" action="admin_operation.php?mode=add_attr_value&id=<?php echo @$row_data['attr_val_id']; ?>&attr_id=<?php echo $attr_id; ?>" method="post">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-lg-4 control-label " for="attr_val">Name</label>
<div class="col-lg-6">
<input id="attr_val" name="attr_val" placeholder="" class="form-control input-md" type="text" value="<?php echo @$row_data['attr_val']; ?>">
<input type="hidden" name="attr_id" id="attr_id" value="<?php echo $attr_id; ?>">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-lg-4 control-label" for="sortorder">Sort Order</label>
<div class="col-lg-6">
<input id="sortorder" name="sortorder" placeholder="" class="form-control input-md" type="text" value="<?php echo @$row_data['sortorder']; ?>">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-lg-4 control-label" for="submit"></label>
<div class="col-lg-6">
<button type="submit" id="submit" name="submit" class="btn btn-primary" value="save">save</button>
</div>
</div>
</fieldset>
</form>
</div>
jQuery
//validation
$(document).ready(function(){
$("#attr_val_form").validate({
errorElement:'div',
rules: {
attr_val: "required",
sortorder: "required"
},
messages: {
attr_val: "Required.",
sortorder: "Required."
}
});
});
//form submit
$('#attr_val_form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'attr_val' : $('input[name=attr_val]').val(),
'attr_id' : $('input[name=attr_id]').val(),
'sortorder' : $('input[name=sortorder]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'admin_operation.php?mode=add_attr_value', // the url where we want to POST
data : formData, // our data object
cache: false,
success: function(data)
{
if($.trim(data)== 'yes')
{
$("#notice")
.show()
.html('<div class="alert alert-success"<strong>Successfully !</strong> record added.</div>')
.fadeOut(3000);
}
else
{
$("#notice")
.show()
.html('<div class="alert alert-danger"<strong>Error !</strong> Record already exist.</div>')
.fadeOut(3000);
}
}
})
// using the done promise callback
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
【问题讨论】:
标签: jquery forms jquery-validate