首页 > 编程 > JavaScript > 正文

JavaScript监听文本框回车事件并过滤文本框空格的方法

2019-11-20 12:39:11
字体:
来源:转载
供稿:网友

本文实例讲述了JavaScript监听文本框回车事件并过滤文本框空格的方法。分享给大家供大家参考。具体如下:

<script type="text/javascript" language="javascript">var username = null;var password = null;//获取文本框  onload = function(){ username = document.getElementById("txtUserName"); password = document.getElementById("txtPassWord");   }//清空文本框function clearTxt(){ username.value = ""; password.value = ""; username.focus(); // document.getElementById('txtUserName').value=""; // document.getElementById('txtPassWord').value=""; // document.getElementById('txtUserName').focus();  } //确定function chkTxt(){ //删除前后空格 username.value = username.value.replace(/(^/s*)|(/s*$)/g,""); password.value = password.value.replace(/(^/s*)|(/s*$)/g,""); //判空 if(username.value.length == 0) { alert("请输入用户名!"); username.focus(); } else if(password.value.length == 0) { alert("请输入密码!"); password.focus(); } else document.getElementById("btnLogin").click();}//回车监听function onkey(){ if (window.event.keyCode==13) {//    document.all["btnLogin"].focus();//    if(document.activeElement.id = "aReset")//判断当前焦点所在的控件的id是aReset//    {//     document.getElementById("aReset").focus();//    } document.getElementById("aLogin").focus(); return false; }}</script>

css代码:

<style type="text/css"> #btnLogin {  width: 0px;  height: 0px;  border-style: none;  background-color: White; } </style>

html代码:

<body onkeydown="onkey()">//把回车监听加入body <form id="login_form" name="login_form" runat="server">  <div>    <label>用户:</label><input id="txtUserName"     runat="server" name="u_name" class="input bold" type="text"/>     <label>密码:</label><input id="txtPassWord"     runat="server" name="u_pass" class="input" type="password"/>     <a href="javascript:chkTxt()" id="aLogin">确定</a>     <%--<a href="javascript:document.forms['login_form'].reset()">    重置</a>--%>     <a href="javascript:clearTxt()" id="aReset">重置</a>    <asp:Button ID="btnLogin" runat="server"   Text="" OnClick="btnLogin_Click" />  </div> </form> </body>

希望本文所述对大家的javascript程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表