1.需求:checkbox复选框有多个,选择其中某几个,保存到数据库中,当加载的时候,需要将原已选择的数据checked到复选框中。以下是用jquery实现。
// 从隐藏的表单域中获取后台赋值的字符串数据转换为JS数组,如:100,111,222
var arr = $("#pro").val().split(",");
// 已checkbox为例子所做的操作。根据name获取所有checkbox对象,循环迭代
$('input[name="check_box"]').each(function(){
// 使用isArray函数判断是否包含在数组中,如果不包含则返回 -1,否则返回元素所在的下标
// 第一个参数为当前checkbox的值,第二个参数为上面定义的数组的值
if($.isArray(this.value, arr)){
// 通过jquery给checkbox设置为选中
$(this).attr("checked", true);
}
});
2.常用JS表达式校验:
1).登陆用户名校验:
用户名长度不超过16位,只能由英文、数字及“_”、“@”、”.”组成"
var loginPattern=/^[a-zA-Z0-9_.@]{0,16}$/; if(!loginPattern.test(login)) { $('#errorInfo_login').css("display","block"); $('#errorInfo_login').html("用户名长度不超过16位,只能由英文、数字及“_”、“@”、”.”组成"); $('#login').css("borderColor","red"); return false; }
2).登陆密码校验:
校验密码,6-16位字符,可使用字母、数字或符号的组合:
var pattern=/^[\x00-\xff]{6,16}$/; if(!pattern.test(password)) { $('#errorInfo_password').css("display","block"); $('#errorInfo_password').html("6-16位字符,可使用字母、数字或符号的组合"); $('#password').css("borderColor","red"); return false; }3).姓名必须为中文校验:
var patrn = /[\u4E00-\u9FA5]/; if (!patrn.test(salesmanName)) { }4).手机号码格式校验:
var patrn = /^\d+$/;
if (!patrn.test(mobile)) {
}
3.时间倒计时函数
function TimeTo(dd){
var t = new Date(dd),//取得指定时间的总毫秒数
n = new Date().getTime(),//取得当前毫秒数
c = t - n;//得到时间差
//如果差小于等于0 也就是过期或者正好过期,则推出程序
if(c <= 0){
document.getElementById('timer').innerHTML ='活动已经结束';
clearInterval(window['ttt']);//清除计时器
return;//结束执行
}
var ds = 60*60*24*1000,//一天共多少毫秒
d = parseInt(c/ds),//总毫秒除以一天的毫秒 得到相差的天数
h = parseInt((c-d*ds)/(3600*1000)),//然后取完天数之后的余下的毫秒数再除以每小时的毫秒数得到小时
m = parseInt((c - d*ds - h*3600*1000)/(60*1000)),//减去天数和小时数的毫秒数剩下的毫秒,再除以每分钟的毫秒数,得到分钟数
s = parseInt((c-d*ds-h*3600*1000-m*60*1000)/1000);//得到最后剩下的毫秒数除以1000 就是秒数,再剩下的毫秒自动忽略即可
document.getElementById('timer').innerHTML = '<p style="margin-top:5px;"> '+d+' 天 '+h+' 小时 '+m+' 分 '+s+' 秒</p>';//最后这句讲定义好的显示 更新到 ID为 timer的 div中
}
(function(){
window['ttt']=setInterval(function(){
//定义倒计时的结束时间,注意格式
TimeTo('${time}');
},1000);//定义计时器,每隔1000毫秒 也就是1秒 计算并更新 div的显示
})();
4.文本域限制输入字符长度
$("textarea[maxlength]").bind('input propertychange', function() {
var maxLength = $(this).attr('maxlength');
if ($(this).val().length > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
}
})