jQuery

Prevent spaces in an input field

Spaces are not allowed

How can you disable spaces in an HTML input field?

To prevent spaces from being entered in an HTML input field using jQuery, you can attach a keydown event handler and check if the pressed key is the spacebar.

HTML

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

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, "");
}
});
});