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.
<div class="demo-wrap">
<input class="demo-input" type="text" />
<div class="demo-input-info">Spaces are not allowed</div>
</div>
$(document).ready(function() {
$(".demo-input").on({
keydown: function(event) {
if (event.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});