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

Asked

Viewed 123 times

1

Hello,

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

However, in the .change i call a field validation function and .keypress i check if user pressed ENTER for me to save in the bank the value of this field.

With this, when the user enters some value in this field and this field is not in agreement, the function of .change points out the problem, but even so the .keypress is triggered and saves the line with the incorrect value.

Is there any way I don’t need to call validation on .keypress also?

Example:

$("campo").change(function(e){
       valida_campo(this);
}).keypress(function(e){
    if(e.which == 13) {
       salva_campo(this);
    }
});
  • The event change does not fire when you insert text. This valida_campo should not be run in the case of Enter? This valida_field `is asynchronous?

  • It is not asynchronous. It fires both triggers when you press ENTER.

  • 2

    I don’t see the need for you to use the event change, whereas in the keypress already does what you need. Use only the keypress to validate and save the field, ie will only save, after the function result valida_campo for true, for example.

  • 1

    I agree with @Douglasgarrido, it could be something like this: https://jsfiddle.net/7hxues6L/

  • Exactly as @Sergio demonstrated.

  • Okay, I understand your position and also agree. Problem solved.

Show 1 more comment

1 answer

2


The change event does not trigger when you insert text, so if you want valida_campo be run before _salva_field_ is run, and ensure that salva_campo is not run case valida_campo fail, then you can do so by removing the logic of the change:

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

Browser other questions tagged

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