'input' event only occurring when loading page

0

Hello, folks at StackOverflow.

I try to make a textarea of a web page that I'm developing check continuously if the typed text is equal to 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 happened once, when loading the page, instead of executing it every time the "field-typing" text changes. I tried to use other events, like 'textchange' and 'change', but I'm still in the same situation.

    
asked by anonymous 19.05.2017 / 17:58

2 answers

3

One option could be to get the element's direct value without having to store it 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><textareaclass="campo-digitacao"></textarea>

And the correct thing 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, not just once.

    
19.05.2017 / 18:11
0

You can use the change event.

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

Or also the event keyup binding on the input.

$(".campo-digitacao").bind('keyup', atualiza);
    
19.05.2017 / 19:40