出于验证目的,我正在使用Jquery验证框架 我有3个按钮可以执行3种不同的操作,请您告诉我如何将这些功能分开调用 Jquery验证框架?
这是我的代码
$(document).ready(function () {
$("#form").validate({
rules: {
"t1": {
required: true
},
"t2": {
required: true
},
"t3": {
required: true
}
},
messages: {
"t1": {
required: "Please, enter t1"
},
"t2": {
required: "Please, enter t2"
},
"t3": {
required: "Please, enter t3"
}
},
submitHandler: function (form) { // for demo
return false; // for demo
}
});
});
$(document).on('click', '#editbtn', function(event ) {
alert('Edit btn clicked');
});
$(document).on('click', '#savebtn', function(event ) {
alert('Save btn clicked');
});
$(document).on('click', '#cancelbtn', function(event ) {
alert('Cancel btn clicked');
});

body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<!-- Start New Category-->
<div class="row-fluid">
<div class="custom35auto">
<div class="portlet box blue">
<div class="portlet-title">
</div>
<div class="portlet-body form" style="display:block;">
<form id="form" method="post" action="#">
<div class="row-fluid">
<div class="span2 pull-left"><label class="text-right" style="margin-top:5px">T1</label></div>
<div class="span9 pull-left"><input type="text" id="t1" name="t1" class="span12" value="" ></div>
</div>
<div class="row-fluid">
<div class="span2 pull-left"><label class="text-right" style="margin-top:5px">T2</label></div>
<div class="span9 pull-left"><input type="text" id="t2" name="t2" class="span12" value="" ></div>
</div>
<div class="row-fluid">
<div class="span2 pull-left"><label class="text-right" style="margin-top:5px">T3</label></div>
<div class="span9 pull-left"><input type="text" id="t3" name="t3" class="span12" value="" ></div>
</div>
<div class="row-fluid">
<div class="span2 pull-left"></div>
<div class="span9 pull-left">
<button id="editbtn" type="submit">Edit</button>
<button id="savebtn" type="submit">Save</button>
<button id="cancelbtn" type="submit">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- End New Category-->
</div>
&#13;
这是我的小提琴
答案 0 :(得分:0)
您不能在表单元素中包含的三个type="submit"
元素,并让它们单独运行。你拥有它的方式,jQuery Validate插件会自动触发每个人的验证/提交。
您可以将其中一个或多个更改为type="button"
元素,然后以编程方式触发验证和/或根据需要提交。
<button id="editbtn" type="button">Edit</button>
<button id="savebtn" type="button">Save</button>
<button id="cancelbtn" type="button">Cancel</button>
这将验证和提交(类似于type="submit"
):
$('#editbtn').on('click', function() {
$('#form').submit();
});
DEMO:http://jsfiddle.net/qq8vn1m7/
这只会验证:
$('#savebtn').on('click', function() {
$('#form').valid(); // validate form
});
DEMO:http://jsfiddle.net/obcnf76e/
然后你可以有条件地检查验证并做一些事情:
$('#savebtn').on('click', function() {
if ($('#form').valid()) {
// do other stuff, save form data, etc.
}
});