2

I been trying to figure out why this does not work with a event listener. This script prevents white space in the beginning of a input so I need to avoid using

this oninput="validate(this)" and convert this script into using a event listener instead I been trying to figure this out for a while now but no luck here is my code.

function validate(input){
  if(/^\s/.test(input.value))
    input.value = '';
}
<input id='noWhiteSpaceAtTheStart' oninput="validate(this)" type='text'/>

3 Answers3

1

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.

cela
  • 2,352
  • 3
  • 21
  • 43
  • 1
    Thank you so much for your help Alec I really appreciate your lesson and advice that you have given to us because of you I improved on having a better understanding of this topic today thanks. –  Jun 07 '18 at 22:12
0

Above code works perfectly fine for me. Can you please attach a breakpoint to check is there something going wrong while the function is called.

Few better ways to implement this: You can use

  • javascript addEventListner on this input text to ensure your code works
  • Use function like onKeyUp
Jinesh
  • 21
  • 8
  • He just does not want to use the current way he is doing it. There are no issues if you read comments. – cela Jun 07 '18 at 21:38
  • @Alec I missed on reading comments as It was just now posted a few minutes ago. And yes in older IE version I don't really think this works. So better to use addEvenListener. – Jinesh Jun 07 '18 at 21:46
0

Try this:

HTML:

<input id='noWhiteSpaceAtTheStart' type='text'/>

Javascript:

function validate(){
  var val = event.target.value;
  if(/^\s/.test(val))
    event.target.value = '';
}
document.getElementById("noWhiteSpaceAtTheStart").addEventListener("input", validate);

Tested on chrome, it works.

kheya
  • 7,546
  • 20
  • 77
  • 109