Logo Luan Morina
Disable spaces in an HTML input field
Spaces are not allowed

How can you disable spaces in an HTML input field?

To disable spaces in an HTML input field using jQuery, you can add a keydown event handler and check whether the pressed key is the space bar.

HTML

<div class="demo-wrap">
 <input class="demo-input" type="text" />
  <div class="demo-input-info">Spaces are not allowed</div>
</div>

CSS

.demo-container {
margin: 0 auto;
padding: 2em;
max-width: 340px;
}
	
.demo-input {
font-size: 1.4em;
}
	
.demo-input-info {
font-size: small;
}

JS

$(document).ready(function() {

$(".demo-input").on({
keydown: function(event) {
if (event.which === 32)
return false;
},

change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
}); 
   Prevent spaces in an input field with jQuery