2

I am new in javascript I want to create textbox which not allows blank space, I don't want to allow paste blank space also. Using jquery I can do it simply but I want to do it using javascript my jquery code is below,

$("input#UserName").on({
  keydown: function(e) {
    if (e.which === 32)
      return false;
  },
  change: function() {
    this.value = this.value.replace(/\s/g, "");
  }
});

I want to do the same thing using javascript help me, please ....

4 Answers4

3

You can use addEventListener to add listener. You can also use onInput to merge both events.

var text = document.getElementById('txtText');
text.addEventListener('input', function(e){
  var keyCode = e.keyCode ? e.keyCode : e.which;
  this.value = this.value.replace(/\s/g, '')
  if(keyCode === 32) return;
})
<input type='text' id="txtText">
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Please use below code to detect space

<input type="text" name="test" id="test">

document.getElementById("test").onkeypress = function (evt) {
        var k = evt ? evt.which : window.event.keyCode;
        if (k == 32) {
            return false;
        }
    }

To detected pest event. Please check below code. It will remove white space onblur event

document.getElementById("test").onblur = function (evt) {
       var x = document.getElementById("test");
       x.value = x.value.replace(/\s/g, "");
}
  • thanks, bro but when I paste anything in the textbox then space is allowed –  Oct 18 '16 at 10:49
  • @SmartDeveloper properly check your textbox id! – Rajeesh Menoth Oct 18 '16 at 10:52
  • I have checked it properly it's working when I type anything in textbox then it not allows space but when I paste anything which considers space then it paste space also –  Oct 18 '16 at 10:56
0

Here the transcription of your jQuery code

var input = document.getElementById("UserName");
if (input) {
  input.addEventListener('keydown', function(e){
    var key = e.which || e.keyCode;
    if (key === 32) {
      e.preventDefault();
      return false;
    }
  });
  input.addEventListener('change', function(){
    this.value = this.value.replace(/\s/g, "");
  });
}
<input type="text" id="UserName">
Robiseb
  • 1,576
  • 2
  • 14
  • 17
0

Try this,

HTML :

<input type="text" value="" maxlength="30" name="email" id="UserName">

Javascript :

document.getElementById("UserName").onkeypress = function(e) {
if (e.which == 32) {
return false;
}
}

Demo : Click here

Rajeesh Menoth
  • 1,704
  • 3
  • 17
  • 33