How to run a function only once and stop it if an onBlur occurs?

Asked

Viewed 48 times

0

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). Is there any way - using pure Javascript - cause this "duplication" to 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.

Grateful from now on!

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, 20);
      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>

2 answers

1


Guys, I got what I wanted by adding a function to the event onBlur within the f_titulo:

<input id="f_titulo" onBlur="once()" type="text">

    function once(){
    document.getElementById('f_titulo').removeEventListener('input', duplica);
}

1

An idea that solves the problem but is not very smart is you create a global variable that serves as a flag

let’s call that flag editCodigo = true

you can create event manager for f_cod that instead of looking 'input' look 'onblur' and this event arrow the flag editCodigo = false

and inside the duplicate there would be a if(editCodigo){....}else{ /*ignora*/}

or would only execute until you have had an input interaction with f_cod


Instead of using this flag approach you can delete the listenner title


Another idea is to make the whole process as you are already doing but just change document.getElementById('f_cod').value = codigoalterado; if the f_cod.value equals f_title.value normalized

because if you have

  • A==a the normalized left contents is equal to 'a' so the function works

however if you add a 'b' in f_cod and then another 'A' in f_title

  • AA==ab the normalized left contents would be 'aa' .... and aa"!="Ab" so the function stops working

if you correct right or left back to works

  • AB==ab or AA==aa
  • Thanks for the reply, @le314u! I ended up removing the bug from my duplication event. I will put in a separate reply, but thank you very much for your help!

Browser other questions tagged

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