JavaScript监听文本框回车事件并过滤文本框空格的方法
本文实例讲述了JavaScript监听文本框回车事件并过滤文本框空格的方法。分享给大家供大家参考。具体如下:
<scripttype="text/javascript"language="javascript"> varusername=null; varpassword=null; //获取文本框 onload=function() { username=document.getElementById("txtUserName"); password=document.getElementById("txtPassWord"); } //清空文本框 functionclearTxt() { username.value=""; password.value=""; username.focus(); //document.getElementById('txtUserName').value=""; //document.getElementById('txtPassWord').value=""; //document.getElementById('txtUserName').focus(); } //确定 functionchkTxt() { //删除前后空格 username.value=username.value.replace(/(^\s*)|(\s*$)/g,""); password.value=password.value.replace(/(^\s*)|(\s*$)/g,""); //判空 if(username.value.length==0) { alert("请输入用户名!"); username.focus(); } elseif(password.value.length==0) { alert("请输入密码!"); password.focus(); } else document.getElementById("btnLogin").click(); } //回车监听 functiononkey() { if(window.event.keyCode==13) { //document.all["btnLogin"].focus(); //if(document.activeElement.id="aReset") //判断当前焦点所在的控件的id是aReset //{ //document.getElementById("aReset").focus(); //} document.getElementById("aLogin").focus(); returnfalse; } } </script>
css代码:
<styletype="text/css"> #btnLogin { width:0px; height:0px; border-style:none; background-color:White; } </style>
html代码:
<bodyonkeydown="onkey()">//把回车监听加入body <formid="login_form"name="login_form"runat="server"> <div> <label>用户:</label><inputid="txtUserName" runat="server"name="u_name"class="inputbold"type="text"/> <label>密码:</label><inputid="txtPassWord" runat="server"name="u_pass"class="input"type="password"/> <ahref="javascript:chkTxt()"id="aLogin">确定</a> <%--<ahref="javascript:document.forms['login_form'].reset()"> 重置</a>--%> <ahref="javascript:clearTxt()"id="aReset">重置</a> <asp:ButtonID="btnLogin"runat="server" Text=""OnClick="btnLogin_Click"/> </div> </form> </body>
希望本文所述对大家的javascript程序设计有所帮助。