我想在锚标记点击事件上使用jQuery验证。这是我的HTML表单和jquery
HTML表单:
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" style="cursor: pointer" >Search</a>
</form>
jQuery代码:
$(document).ready(function () {
$("#submit").click(function () {
$("#search_booking").validate({
rules: {
job_date: {required: true}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function (form) {
form.submit();
}
});
});
});
点击锚标记后,它不会将表单提交给表单操作。
提前致谢。
答案 0 :(得分:2)
您需要在dom ready中初始化验证器插件,然后在提交按钮单击中,调用表单提交事件并进行验证。
$(document).ready(function() {
$("#search_booking").validate({
rules: {
job_date: {
required: true
}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function(form) {
form.submit();
}
});
$("#submit").click(function() {
$("#search_booking").submit();
});
});
&#13;
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" style="cursor: pointer">Search</a>
</form>
&#13;
答案 1 :(得分:1)
这与接受的答案非常相似,除了两件事......
我正在使用event.preventDefault()
来阻止锚元素的默认行为。
$("#submit").click(function(e) {
e.preventDefault();
$("#search_booking").submit();
});
我添加了href="#"
,以便.preventDefault()
可以正确阻止跳转到页面顶部,并保持HTML标准的合规性。
<a id="submit" href="#" style="cursor: pointer">Search</a>
$(document).ready(function() {
$("#search_booking").validate({
rules: {
job_date: {
required: true
}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function(form) {
// form.submit(); //default plugin behavior
alert('submission'); // only for demo
}
});
$("#submit").click(function(e) {
e.preventDefault();
$("#search_booking").submit();
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" href="#" style="cursor: pointer">Search</a>
</form>