You can use input
event or even keyup
event. It fires everytime the input's text changes. As far as I know, input
is supported in IE9+ and other modern browsers, and keyup
is supported in all browsers.
Example with input
event:
var input = document.getElementById("noWhiteSpaceAtTheStart");
input.addEventListener('input', function() {
if(/^\s/.test(input.value)) {
input.value = '';
}
});
Example with keyup
event, this is a little uglier than the latter solution because the user can see the space being inputted and removed:
var input = document.getElementById("test");
input.addEventListener('keyup', function() {
if(/^\s/.test(input.value))
input.value = '';
});
Inputs that are changed with JavaScript must be triggered manually, and this can be done easily with jQuery by the following(may not work on native JavaScript events, have not tested):
var input = $("#input");
input.val("I am going through changes mom");
input.trigger("change");
Although, using pure JavaScript to do this is a little more complicated. Here is a link to help with that if needed
Here is a working codepen for you.