views:

24

answers:

2

I have a form with an input field where a user enters a unique identifier. I then have some jQuery code that upon the user moving away from the input field (blur) goes out and fetches details about the part and populates some fields on the page. The problem is if the user clicks the submit button before moving out of the input field the jQuery code never has a chance to load in the data and populate the necessary fields. Whats the best way to go about doing this? I thought about maybe setting the focus to body and then having an infinite loop that keeps checking the page until all fields that should be filled in have been filled in but I feel like some sort of event based solution would be better than unpredictable infinite loops. Any ideas?

+3  A: 

Give the form an onsubmit event.

Have that event return false unless all the form fields are populated correctly.

In jQuery:

$("#formname").submit(function()
 { if (condition_not_met) return false; });

This will block the form from submitting until everything is in place.

The blocking will not work with JavaScript disabled, but seeing as you're using Ajax to fetch the correct fields, that probably won't matter.

Pekka
This is sort of the simple solution. I thought about doing this but was hoping for a slightly more streamlined solution where the user wouldn't have to then click the submit button again.
blcArmadillo
@blcArmadillo easy: Have my function from above set a flag `submitWhenPossible = true` when the condition is not met. Have your Ajax success callback check for that flag, and if it is set to true, do a programmatic submit: `$("#formname").submit();` Never use infinite loops in JS, they can crash your user's browser. However, a delayed submit may cause confusion, as users are used to see some browser activity (throbber starting, page changing...) when clicking a button. Not sure whether this is a good idea from that point of view, but try it out.
Pekka
A: 

I'm guessing you are making an ajax call in the blur function? Could you disable the submit button (either on page load or on blur), and then enable it in the ajax callback?

Michael Finger