0

I'm having trouble with the way javascript execute the code (async)

I have this small piece of code that will trigger events and check the value of 'valid'.

My problem is that 'valid' is always true when entering the if statement because the events have not finished processing yet :

valid = true;

$(this).find('input').trigger('blur');
//valid will be modified in the triggered events

if(valid){
    //Do something
}

So I'd like to wait till the events are finished to enter the statement, but trigger doesn't take a callback

I have seen some questions about this already solved but I didn't understand them and how to implement them.

What should I use to solve this ?

7
  • 1
    Where's the code that gets executed when the input is blurred? Commented Mar 13, 2015 at 16:27
  • 1
    Is this related/a duplicate? In theory it should be synchronous, so yes - we need to see your blur handler. Commented Mar 13, 2015 at 16:27
  • 1
    What is $(this)? why don't you just have an event function - $('input').on('blur', function(){}); Commented Mar 13, 2015 at 16:28
  • No need to use trigger. You can directly use blur on element. It's better to post more code for helping. Commented Mar 13, 2015 at 16:32
  • @Adjit $(this) is a form, I'm inside a function that's just why I used $(this) Commented Mar 13, 2015 at 16:32

3 Answers 3

0

Thanks to JamesThorpe I found the answer I was looking for :

 valid = true;
 $.when($(this).find('input').trigger('blur')).done(function(){
     if(valid){
         //Do something
     }
 });

And now the if statement only gets executed after the events are triggered

Sign up to request clarification or add additional context in comments.

1 Comment

You should delete this question it is a duplicate
0

As you want to have it triggered on blur, you can do it like this:

$(this).find('input').on('blur', function(){
    if(valid){
        //Do something
    }
});

Note that the function will be triggered on all blur events. To have it only once use .one()

Comments

0

I don't understand why you are using trigger. I think you can directly use blur event:

$(this).find('input').blur(function(){
    if(valid)
      //do something
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.