call .keypress (e) only if .change (e) is OK

1

Hello,

I need some help. I have a input[type=text] field that I have triggers on it, a .change trigger and a .keypress .

However, in .change I call a field validation function and in .keypress I check if the user pressed ENTER to save the value of that field to the database.

So when the user types some value in this field and this field does not agree, the .change function points the problem, but even then the .keypress is triggered and saves the line with the wrong value.

Is there any way I do not need to call validation in .keypress too?

Example:

$("campo").change(function(e){
       valida_campo(this);
}).keypress(function(e){
    if(e.which == 13) {
       salva_campo(this);
    }
});
    
asked by anonymous 05.01.2017 / 11:58

1 answer

2

The change event does not fire when you insert text, so if you want valida_campo to be run before _salva_field is run, and ensure that salva_campo is not run if valida_campo fails, then you can do so by removing logic of change :

$("input").keypress(function(e) {
    var valido = valida_campo(this);
    if (valido && e.which == 13) {
        salva_campo(this);
    }
});
    
05.01.2017 / 12:33