Fork me on GitHub

实用js代码片段【一】

表单验证

获取单选值

1
2
3
4
5
6
7
8
9
10
11
function getSex(){
var value="";
var radio=document.getElementsByName("gender");
for(var i=0;i<radio.length;i++){
if(radio[i].checked==true){
value=radio[i].value;
break;
}
}
alert(value);
}

过滤数字,自符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
window.onload=function (){
var id=document.getElementById('id');
var clearNumber=function (tThis){
var _v=tThis.value;
tThis.value=_v.replace(/\D/g,""); //过滤数字
tThis.value=_v.replace(/[^\u4e00-\u9fa5]/g,""); //过滤中文
}
txt.onblur = function(){
clearNumber(this);
}
txt.onfocus = function(){
clearNumber(this);
}
txt.onkeyup = function(){
clearNumber(this);
}
}

限制用户输入的字符数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
window.onload=function (){
var id=document.getElementById("id");
clearmaxlength=function (tThis){
var _v=tThis.value,
_vLen=_v.length,
dataLen=tThis.getAttribute('data-length'),
subLen=dataLen;
if(_vLen>dataLen) tThis.value=_v.substr(0,subLen);
}
txt.onblur = function(){
clearmaxlength(this);
}
txt.onfocus = function(){
clearmaxlength(this);
}
txt.onkeyup = function(){
clearmaxlength(this);
}
}

回车提交

1
2
3
4
5
6
7
8
9
10
window.onload=function (){
var txt=document.getElementById("txt");
txt.onkeyup=function (e){
e= e || window.event;
var keycode=e.keyCode || e.which || e.charCode;
if(keycode===13){
alert("回车提交成功!")
}
}
}

关键字过滤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.onload=function (){
var txtfilter=document.getElementById("id");
txtfilter.onclick=function (){
words=[
"JavaScript",
"美女",
/[外]{1}.{0,3}[挂]{1}/
],
txtLen=words.length;
for(var i=0;i<txtLen;i++){
txtfilter.value=txtfilter.value.replace(words[i],"***");
}
}
}

未完待续。。。

当然,你也可以查看这里。

点击查看更多

据说帅的人都赏给博主几块钱零花钱。