DOM基础教程之使用DOM设置文本框

1.控制用户输入的字符个数

对于单行文本框和密码输入框,可以利用maxlength属性控制用户输入的字符个数。
对于多行文本,maxlength为自定义属性,其值最多输入的字符的个数,在onkeypress事件发生时则调运返回LessThan()函数返回值,函数如下

<textarea name="comments" id="comments" cols="40" rows="4" maxlength="50" onekeypress ="return LessThan(this);"></textarea>
详细代码

代码如下:

<script language="javascript">

function LessThan(oTextArea){

    //返回文本框字符个数是否符号要求的boolean值

    return oTextArea.value.length < oTextArea.getAttribute("maxlength");

}

</script>

<form method="post" name="myForm1" action="addInfo.aspx">

<p><label for="name">请输入您的姓名:</label>

<input type="text" name="name" id="name" class="txt" value="姓名" maxlength="10"></p>

<p><label for="comments">我要留言:</label><br>

<textarea name="comments" id="comments" cols="40" rows="4" maxlength="50" onkeypress="return LessThan(this);"></textarea></p>

<p><input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" class="btn">

<input type="reset" name="btnReset" id="btnReset" value="Reset" class="btn"></p>

</form>

2.设置鼠标经过自动选择文本

首先是鼠标经过时自动聚焦 onmouseover = "this.focus"

其次是 onfocus = "this.select()"
代码实例:

代码如下:

<form method="post" name="form1" id="form1" action="addInfo.aspx">

<input type="text" name="name" id="name" class="txt" value="姓名" onmouseover="this.focus()" onfocus="this.select()">

</form>

对于多个代码实例,可以使用以下代码进行聚焦

代码如下:

<script type="text/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>

            <form method="post" name="myForm1" action="addInfo.aspx">

                <p>

                    <label for="name">请输入您的姓名:</label>

                    <input type="text" name="name" id="name" class="txt" value="姓名">

                </p>

                <p>

                    <label for="passwd">请输入您的密码:</label>

                    <input type="password" name="passwd" id="passwd" class="txt">

                </p>

                <p>

                    <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" class="btn">

                    <input type="reset" name="btnReset" id="btnReset" value="Reset" class="btn">

                </p>

            </form>

dom

相关推荐