/**
* 根据输入框的不同类型来判断
* @param {Object} flag
* @param {Object} inputArg
*/
function addMessage(flag,inputArg){
if(flag){
//显示正确信息文本
addText(inputArg.targetId,inputArg.onSuccessText);
//切换样式
addClass(inputArg.targetId,inputArg.onSuccessClass);
}else{
//显示错误信息文本
addText(inputArg.targetId,inputArg.onErrorText);
//切换样式
addClass(inputArg.targetId,inputArg.onErrorClass);
}
}
/**
* 给目标控件添加显示的文本信息
* @param {Object} targetId 目标控件id
* @param {Object} text 需要显示的文本信息
*/
function addText(targetId,text){
if(text==undefined){
text="";
}
$("#"+targetId).html(" "+text);
}
/**
* 切换样式
* @param {Object} targetId 目标控件id
* @param {Object} className 显示的样式名称
*/
function addClass(targetId,className){
if(className!=undefined && className!=""){
$("#"+targetId).removeClass();
$("#"+targetId).addClass(className);
}
}
/code]
每次不同的验证都会涉及到 添加文本消息,表单元素的不同添加文本消息,和样式的替换,于是分离出来上面三个公用方法。
在源码中 if($(this).attr("type")=="radio" || $(this).attr("type")=="checkbox") 这句是比较重要的一句,因为它涉及到了验证元素的扩展。
四. 使用例子
文本框测试样图
输入文本框获得焦点提示
输入文本框失去焦点错误提示
输入文本验证正确提示
radio 测试样图
checkbox 测试样图
checkbox 验证失败提示
checkbox 验证成功提示
测试代码
[code]
<script language="JavaScript" src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script language="JavaScript" src="jquery-extend-1.0.0.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("#txtName").checkRequired({
required:true,
onFocusText:"必填项",
onFocusClass:"notice",
onErrorText:"错误提示",
onErrorClass:"error",
onSuccessClass:"correct",
targetId:"txtNameTip"
});
$("#rdbMan").checkRequired({
required:true,
onFocusText:"必填项",
onFocusClass:"notice",
onErrorText:"错误提示",
onErrorClass:"error",
onSuccessClass:"correct",
targetId:"txtSexTip"
});
$("#rdbWoman").checkRequired({
required:true,
onFocusText:"必填项",
onFocusClass:"notice",
onErrorText:"错误提示",
onErrorClass:"error",
onSuccessClass:"correct",
targetId:"txtSexTip"
});
$("#rdbMan1,#rdbWoman2,#rdbMan3,#rdbWoman4").checkRequired({
required:true,
onFocusText:"必填项",
onFocusClass:"notice",
onErrorText:"错误提示",
onErrorClass:"error",
onSuccessClass:"correct",
targetId:"txthobbyTip"
});
});
</script>
<p>
<label>姓名:</label><input type="text" id="txtName" value=""/><span id="txtNameTip"></span>
</p>
<p>
<label>性别:</label>
<span>
<input id="rdbMan" type="radio" name="sex" value="男" />男
<input id="rdbWoman" type="radio" name="sex" value="女" />女
</span>
<span id="txtSexTip"></span>
</p>
<p>
<label>爱好:</label>
<span>
<input id="rdbMan1" type="checkbox" name="hobby" value="hobby1" />aa
<input id="rdbWoman2" type="checkbox" name="hobby" value="hobby2" />bb
<input id="rdbMan3" type="checkbox" name="hobby" value="hobby3" />aa
<input id="rdbWoman4" type="checkbox" name="hobby" value="hobby4" />bb
</span>
<span id="txthobbyTip"></span>
</p>