Home > Article > Web Front-end > JavaScript method to listen to the carriage return event of the text box and filter the spaces in the text box_javascript skills
The example in this article describes the method of JavaScript listening to the carriage return event of the text box and filtering the spaces in the text box. Share it with everyone for your reference. The details are as follows:
<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 code:
<style type="text/css"> #btnLogin { width: 0px; height: 0px; border-style: none; background-color: White; } </style>
html code:
<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>
I hope this article will be helpful to everyone’s JavaScript programming design.