How to limit the amount of characters that one input text assigns to another in Javascript?

Asked

Viewed 74 times

-1

Dear ones, researching about my question, I found something similar in ONLY in English, but I still can’t limit the characters that the "Title" input duplicates in the "Material Code", even though I assign a maxlength=20 in that.

To be clear, I have two inputs: what is typed in the "Title" is duplicated in the "Material Code" with the appropriate normalizations (i.e. space conversion and character removal). However, the "Material Code" field cannot be more than 20 characters (which is ignored during "duplication").

How to proceed in this case? Grateful from now on!

P.S.: I don’t think I should do this, but next to that question, I have another question, which if someone could perhaps enlighten me, would also be of great help: is there any way to make this "duplication" occur only once? Something like a onBlur in which if the user edits the "Material Code" field and comes to edit the "Title" as well, no more interference will occur in that field, since this can be edited by the same user.

document.getElementById('f_titulo').addEventListener('input', duplica);

function duplica() {
      const codigomaterial = document.getElementById('f_titulo').value;
      const codigoalterado = codigomaterial.normalize('NFD').replace(/([\u0300-\u036f]|[^_0-9a-zA-Z\s])/g, '').replace(/ /g, "_").toLowerCase();
      document.getElementById('f_cod').value = codigoalterado;
};
<input id="f_titulo" type="text" maxlength="60" placeholder="Título">

<input id="f_cod" type="text" maxlength="20" placeholder="Código do Material" required>

1 answer

3


Use the . substring method()

This method allows you to take only the first 20 letters of the "Title" input, how? Tell this method that you want to pick from the first letter which is index 0 to the twentieth letter which is index 19.

This way it will always take the substring from index 0 to index 19, even if the input string is smaller, the method will ignore, and it will pick up as far as it goes.

document.getElementById('f_titulo').addEventListener('input', duplica);

function duplica() {
      const codigomaterial = document.getElementById('f_titulo').value;
      const codigoalterado = codigomaterial.normalize('NFD').replace(/([\u0300-\u036f]|[^_0-9a-zA-Z\s])/g, '').replace(/ /g, "_").toLowerCase().substring(0, 19);
      document.getElementById('f_cod').value = codigoalterado;
};
<input id="f_titulo" type="text" maxlength="60" placeholder="Título">

<input id="f_cod" type="text" maxlength="20" placeholder="Código do Material" required>

  • 1

    Very good, @Laks Castro! Thank you, man! You helped a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.