Click here to Skip to main content
16,004,887 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi sir,
I wrote one javascript code to prevent "space" in textbox. Its working fine in Internet explorer, but it is not working in mozilla firefox. I attached the code below for your reference. Kindly give me the solution for this problem.


Default3.aspx
*******************
ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        function AvoidSpace() {
            if (event.keyCode == 32) {
                event.returnValue = false;
                return false;
            }
        }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:TextBox ID="txtEmpName" runat="server" onkeypress="return AvoidSpace()"></asp:TextBox>
    </div>
    </form>
</body>
</html>
Posted
v2

Problem
You have not passed the event into the function.

Solution
1. You need to do like below.
XML
<asp:TextBox ID="txtEmpName"
             runat="server" 
             onkeypress="return AvoidSpace(event)">
</asp:TextBox>


2. And use this event in the function. Modify the function as below.
JavaScript
function AvoidSpace(event) {
    var k = event ? event.which : window.event.keyCode;
    if (k == 32) return false;
}

Quote:
The onkeypress event is not fired for all key types in all browsers. For details, please see the table below.
To get the pressed key, use the keyCode, charCode and which event properties.
Refer - onkeypress event | keypress event[^].

window.event.keyCode is for Internet Explorer.
event.which is for other browsers.

DEMO
onkeypress Event Demo - restrict space key[^].
 
Share this answer
 
v2
You only return false and never true. You should return something on all cases.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900