jquery - prevent this race condition

Go To StackoverFlow.com

1

I have a bunch of textboxes on a page and a submit button. I have wired up the TextChanged event of the textbox to execute a server-side method. The user enters values into the textboxes, tabs out to the next textbox (triggering the textchanged event) and finally clicks the submit button which invokes another server-side method. All the functions are asynchronous. The submit method needs to be executed only after the textchange method is finished as they both share the same data. The issue is sometimes the textchange method takes slightly longer to finish, and the submit method is triggered before the textchange function is completed. How do I prevent this? How do I lock/queue functions?

2012-04-03 22:00
by tempid


1

Don't lock or queue anything! Just disable the the submit button until the change event + ajax is complete.

$('#submitBtn').attr('disabled', 'disabled');

Or for jQuery 1.6+:

$('#submitBtn').prop('disabled', true);

And when the change ajax finishes:

$('#submitBtn').attr('disabled', '');//or $('#submitBtn').prop('disabled', false)
2012-04-03 22:04
by gdoron
I've thought of this before but the issue in my case is that when the user is in the last textbox, they don't tab out to trigger the change function of the textbox. They click on the submit button directly (which then triggers the change function of the textbox). If I disable the submit, they don't click the button or anywhere else on the form to trigger the change. Any other suggestions - tempid 2012-04-03 22:19
@enigma. Then save a flag with the true when all the change events are done. Capture the submit event and if the flag is false, prevent default. How is that - gdoron 2012-04-04 08:29
Thank you, this is what I ended up doing and it seems to working fine - tempid 2012-04-18 17:06
@enigma. Did it take you 15 days to implement that line in your code? :)gdoron 2012-04-18 17:08
Lol no, I got sidetracked with something else : - tempid 2012-05-05 03:07


0

Take a look at Ben Alman's jQuery Queueing plugin http://benalman.com/projects/jquery-message-queuing-plugin/ from the sounds of it that might be what you need.

2012-04-03 22:25
by Brett McCarty
Ads