文本框是表单中与用户打交道最多的元素之一,它包括单行文本框和多行文本框
更广义的还可以包括密码输入框。
控制用户输入字符个数
对于单行文本框和密码输入框而言,可以利用自身的maxlength属性控制用户输入字符的个数;
而对于多行文本框
以上代码中maxlength为自定义属性(
在onkeypress事件发生时则调用返回LessThan()函数的返回值,函数如下:
function LessThan(oTextArea){
//返回文本框字符个数是否符号要求的boolean值
return oTextArea.value.length < oTextArea.getAttribute("maxlength");
}
实例:
控制textarea的字符个数
<script language="javascript">
function LessThan(oTextArea){
//返回文本框字符个数是否符号要求的boolean值
return oTextArea.value.length < oTextArea.getAttribute("maxlength");
}
</script>
设置鼠标经过时自动选择文本
通常是在用户名、密码等文本框中希望鼠标指针经过时自动聚焦,并且能够选中默认值以便用户直接删除。
首先是鼠标指针经过时自动聚焦,代码如下
onmouseover="this.focus()"
其次是聚焦后自动选中所有文本,代码如下:
onfocus="this.select()"
如:
javascript分离实现自动选择文本
<script language="javascript">
function myFocus(){
this.focus();
}
function mySelect(){
this.select();
}
window.onload = function(){
var oForm = document.forms["myForm1"];
oForm.name.onmouseover = myFocus;
oForm.name.onfocus = mySelect;
}
</script>