How to disable space on smart phone using jQuery in ASP.Net

Last Reply on Jul 21, 2017 08:45 AM By power

Posted on Jul 18, 2017 02:02 AM

Hello,

I am using the code below to allow certain characters into username or other textboxs. The main goal is if user accidently touches spacebar, the code should prevent spacebar from adding any space. The code works fine on my laptop. However, this code doesn't work on smartphone. I checked it on my smartphone (Samsung) and it adds space when I click spacebar. Can you tell me what is missing from this code to prevent space when a user uses smartphones and touches spacebar?

 function IsAlphaNumericUsername(e) {
            var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
            var ret = ((keyCode == 13) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
            document.getElementById("errorUsername").style.display = ret ? "none" : "inline";
            return ret;
        }

 

Posted on Jul 18, 2017 02:37 AM Modified on on Jul 19, 2017 02:38 AM

Hi power,

What you can do is simply replace white space character like below.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" id="txtNoSpaces" onpaste="return false;" />
    </div>
    <div>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#txtNoSpaces').keyup(function () {
                    str = $(this).val()
                    str = str.replace(/\s/g, '')
                    $(this).val(str)
                });
            });
        </script>
    </div>
    </form>
</body>
</html>

Demo

 


Posted on Jul 18, 2017 10:31 AM Modified on on Jul 20, 2017 08:32 AM

Check with the below code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('[ID*=txtUsername]').keyup(function () {
                str = $(this).val()
                str = str.replace(/\s/g, '')
                $(this).val(str)
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtUsername" runat="server" onpaste="return false;"></asp:TextBox>
    </div>
    </form>
</body>
</html>