Home > Enterprise >  I am seeing 4th character in output after using substr(0,3) on input characters
I am seeing 4th character in output after using substr(0,3) on input characters

Time:10-31

I have a problem with an input, I am validating max length with this function, but in my html whenever I enter more than 3 values, it gets added to the input answer output when it should only display max 3 values, I'm not sure why.

And no, I can not use maxlength, because I need to create this dynamically, sometimes my input field has type text, and sometimes it changes to a random number, not always 3.

As you can see on the picture, I typed 333, then input answer was 333, I added another 3 which I do not see in the input field and the answer changed to 3333 which shouldn't happen.

enter image description here

Example:

const input = document.querySelector('input');
const log = document.getElementById('values');

input.addEventListener('input', updateValue);
input.addEventListener('input', cutText);

function cutText(e) {
      e.target.value = e.target.value.substr(0, 3);
      console.log(e.target.value)
    }

function updateValue(e) {
  log.textContent = e.target.value;
}
<input placeholder="Enter some text" name="name"/>
<p id="values"></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This is because of the ordering of the event, You are first updating the value of the log element and then setting the value of the input.

If you have input aaaa then it will first set the value of the log element to aaaa and then set the input as aaa

If you would place curText first and then updateValue then It will behave as expected

input.addEventListener('input', cutText);
input.addEventListener('input', updateValue);

const input = document.querySelector('input');
const log = document.getElementById('values');

input.addEventListener('input', cutText);
input.addEventListener('input', updateValue);

function cutText(e) {
  e.target.value = e.target.value.substr(0, 3);
  console.log(e.target.value)
}

function updateValue(e) {
  log.textContent = e.target.value;
}
<input placeholder="Enter some text" name="name" />
<p id="values"></p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related