Helpha Helpha - 1 month ago 9
ASP.NET (C#) Question

Blocking spaces ASP MVC and Javascript

I'm trying to validate the code that users enter in my view. I want it to be MAJ and only letters and numbers. So no ""/(!/ or spaces. Everything works just fine except for the spaces...

Here's the code

@Html.TextBoxFor(m => m.Code, new { @onkeydown = "onKeyDown(this);", @class = "input-visual-helper form-control", placeholder = @MyProject.Resources.home.ActivationCode })


<script type="text/javascript">
function onKeyDown(a) {
var charCode = (a.which) ? a.which : event.keyCode

setTimeout(function () {
a.value = a.value.toUpperCase();
}, 1);

return ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8 || (charCode >= 48 && charCode <= 57));
}
</script>


I did a console.log of the condition in the return and it logs false when I type the space (code 32). I even tried doing if(charCode ==32) return false. Still not working... The interface keeps doing a space in the textbox.

Any help would be greatly appreciated.

Thanks

Answer

        $("#jam").keydown(function (e) {
             if (e.keyCode == 32) { 
               return false; 
             }
        });
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  
</head>
<body>
<input id="jam"/>
</body>
</html>

Something like this?

 <script type="text/javascript">
    $("#targetElement").keydown(function (e) {
         if (e.keyCode == 32) { 
           return false; 
         }
    });
 </script>

https://jsbin.com/didohiloni/1/edit

For the MVC textbox you would append new { id = "youid" } in there

Comments