locked
Do not allow a textbox to have a space between text RRS feed

  • Question

  • User1052662409 posted

    Hi All,

    I am looking for a solution, so that I can restrict user to have a space in a textbox's text.

    I got one as below

           <script>
            function RestrictSpace() {
                if (event.keyCode == 32) {
                    event.returnValue = false;
                    return false;
                }
            }
    	</script>

    It is working fine. It doesn't allow user to type space using space-bar key. But If I copy a text like Alex John, it accept it, as it have the space between name.

    I also want to restrict it like if I paste Alex John it should itself convert like AlexJohn.

    Please Suggest

    Friday, March 30, 2018 5:26 PM

Answers

All replies

  • User-369506445 posted

    hi

    please try below code :

    <input type="text" id="txt"/>
    
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        $('#txt').on("input", function () {
            $(this).val($(this).val().replace(/ /g, ""));
            //or
            //$(this).val('');
            //alert("you can't insert space on text-box");
    
        });
    </script>

    I hope that be helpful

    Saturday, March 31, 2018 2:40 PM
  • User-1838255255 posted

    Hi demoninside9,

    According to your description and needs, please check the following sample code:

    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
        <script>
            $(function () {
                $("#Text1").blur(function () {
                    debugger;
                    var txt = $(this).val();
                    var newtxt = txt.replace(/\ /g, '');
                    $(this).val(newtxt);
                });
            });
        </script>
    </head>
    <body>
        <input id="Text1" type="text" />
    </body>

    Best Regards,

    Eric Du 

    Monday, April 2, 2018 5:58 AM
  • User516094431 posted

    As per you need, you can use one another option that "Disable Cut Copy Paste".

    Disable cut, copy and paste in textbox using jquery, javascript

    Not Allow Space on Key Press and Paste 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 2, 2018 6:22 AM