Search code examples
javascripttrimspaces

Trim white-spaces from all input fields using JavaScript


Looking for pure JavaScript works specially in IE to remove all extra white-spaces from all inputs (text and textarea).

Here is the jQuery version that works but I want it in JavaScript:

function TrimText(el) {
 el.value = el.value.
 replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
 replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
 replace(/\n +/, "\n"); // removes spaces after newlines
 return;
}

What is best approach to convert this to JavaScript?

$j(function () {
 $j("textarea").change(function () {
    TrimText(this);
 });

 $j("input").change(function () {
    TrimText(this);
 });
});

Solution

  • If you want to apply this to all inputs currently in the page:

    document.querySelectorAll('input, textarea').forEach(function(el) {
      el.addEventListener('change', function(ev) { TrimText(ev.target); });
    });
    

    If you want to apply it to all inputs currently in the page, and all inputs created in the future:

    document.addEventListener('change', function (ev) {
      if(ev.target.tagName === 'INPUT' || ev.target.tagName === 'TEXTAREA')
        TrimText(ev.target);
    });
    

    This works by using a mechanism called bubbling. Events in Javascript bubble up through the DOM and finally reaches the document element. So, we listen to the events in the document element and filter the events by the tag name of the target.

    This is how JQuery works internally, and this approach is applicable to other things you can do in JQuery.