我有一个注册表单,我希望在其中应用bootstrap validator,如果表单成功填写,它应该转到后端脚本将运行并提交数据的ajax部分。
表格
<form data-toggle="validator" role="form" id="signup-form" method="post">
<input type="text" class="form-control" placeholder="Name" name="cname" id="cname" required>
<input id="email" type="email" class="form-control" placeholder=" email" name="email" data-error="email address is invalid" required>
<input type="password" class="form-control out-box" placeholder="Password" name="password" id="password" required>
<button type="submit" class="btn btn-primary" id="submit_form">SIGN UP</button>
</form>
Ajax代码
$("#submit_form").click(function()
{
var cname = $("#cname").val();
var email = $("#email").val();
var password = $("#password").val();
var dataString = 'cname='+ cname + '&email='+ email + '&password='+ password ;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>/student/register",
data: dataString,
cache: false,
success: function(result){
console.log(result);
}});
return false;
});
问题是,如果表单为空或有任何问题并且我点击了提交按钮,则有问题的区域会在引导验证程序中突出显示,但在此之后也会执行ajax代码。
我希望ajax代码只应在所有验证都已完成并且表单没有问题时运行。
答案 0 :(得分:0)
尝试以下方式。
$('#signup-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
var cname = $("#cname").val();
var email = $("#email").val();
var password = $("#password").val();
var dataString = 'cname='+ cname + '&email='+ email + '&password='+ password ;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>/student/register",
data: dataString,
cache: false,
success: function(result){
console.log(result);
}});
return false;
}
})