本文實例講述了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程序設計有所幫助。