Input event only happening when loading the page

Asked

Viewed 143 times

0

Hello, folks at Stackoverflow.

I try to make a textarea of a web page I am developing continuously check whether the typed text is the same or different from a predefined phrase, according to the javascript code and jquery below:

var atualiza = function(){

var texto = $(".campo-digitacao").text();
var frase = $(".frase").text();

if (texto==frase){

    console.log("TEXTO IGUAL");

    } else if (texto!=frase){

    console.log("TEXTO DIFERENTE");

    }

console.log("escreveu");
}


$(".campo-digitacao").on('input',atualiza());

However, I only get two notifications via console ("DIFFERENT TEXT" and "wrote"), as if the 'input' event only happens once, when loading the page, instead of it running every time the "input field" text changes. I tried to use other events like textchange and change, but I’m still in the same situation.

2 answers

3

An option could be to get the direct value of the element without having to store in a variable:

var frase = 'TESTE';

$(".campo-digitacao").on('input', atualiza);

function atualiza() {
  if (this.value == frase) {
    console.log("TEXTO IGUAL");
  } else {
    console.log("TEXTO DIFERENTE");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="campo-digitacao"></textarea>

And the right thing to do is to use .on('input',atualiza); instead of .on('input',atualiza()); so that the scope is transferred to the function and that it is invoked whenever the event occurs, and not only once.

  • 2

    I didn’t even notice .on() was the same element :) Nicely caught. You can add a comment to the problem .on('input',atualiza());? so the answer is complete +1

  • Thank you @Sergio

0

You can use the event change.

$(".campo-digitacao").on('change', atualiza);

Or also the event keyup bindando in input.

$(".campo-digitacao").bind('keyup', atualiza);
  • The function bind is discontinued and no longer interesting to use.

Browser other questions tagged

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