form表单添加ajax校验
<button type="button" id="register" class="btn btn-primary btn-block btn-flat" onclick="register()">Register</button>
button的类型由submit更改为button,添加onclick事件。
function register() {
if($("#terms").val() != "1"){
alert("Do you agree to the terms?");
return false;
}else{
$("#rForm").submit();
}
}
表单
<form:form modelAttribute="registerDTO" id="rForm" action="${pageContext.request.contextPath}/register/register" method="post">
这里button也可以不添加onclick事件,js采用
$("#register").click(function () {
//do something
})
同时表单的提交也可以不放在js中,采用οnsubmit=”return checksubmit()方式检验表单数据的合法性。
这里关于checkbox的取值与设值需要注意一下,
设值:οnclick=”this.value=this.checked?1:0”。
取值:$(“#terms”).val()
1、获取单个checkbox选中项(三种写法)
$("input:checkbox:checked").val()
或者
$("input:[type='checkbox']:checked").val();
或者
$("input:[name='ck']:checked").val();
2、 获取多个checkbox选中项
$('input:checkbox').each(function() {
if ($(this).attr('checked') ==true) {
alert($(this).val());
}
});
checkbox的具体取值参见http://www.jb51.net/article/46469.htm
以上代码完成后,点击button始终是无反应,打开F12调试工具,发现函数不存在。最终发现是由于button嵌套在form内部,导致表单没法提交。具体原因还不是太明白||====。