I have a HTML form with a couple of radio buttons. The first few are normal radios, but the last one is associated with a text box. I'd like to run some JavaScript validation to warn users when they select "other" without providing a value using the text box.
Functional HTML + JS is linked below, but the rough outline of the HTML is:
<ul>
<li>
<input type="radio"/> foo
</li>
<li>
<input type="radio"/> bar
</li>
<li>
<input type="radio"/> other, please specify:
<input type="text"/> <span class="error">please provide a value</span>
</li>
</ul>
I have some JavaScript to focus the text box when the Other radio is checked, and vice versa.
The problem
I can't figure out which events to hook into to get the validation working as I'd like.
Test cases I'm having trouble with:
- Warning should never be visible in this sequence of actions:
- Start with the Foo radio selected, and no text in the textbox.
- Give the text box focus (e.g. click it); the Other radio is automatically checked.
- Select Foo radio
- Warning should be first shown when I perform step 3:
- Start with Foo radio selected, and no text in the textbox.
- Give the text box focus (e.g. click it); the Other radio is automatically checked.
- Don't type in the text box, and continue on with the rest of the form (i.e. give focus to something else).
Things I've tried
Validating on the text box's blur (or change) event. the warning flickers into existence at case 1 step 3. This is because the blur happens before the Foo radio becomes selected.
Validating on the ul's blur event: it doesn't have one.
On the text box's blur event, add a handler for document's mouseup event. On the mouseup, validate and remove the handler. This works when the loss of focus in case 2 step 3 is caused by clicking somewhere else. It doesn't work when the loss of focus is caused by the keyboard, or tabbing away from the window. Or when multiple mouse clicks overlap in time. Fixing these seems like it's going to make things overly complicated.
Handling the text box's blur, and using
setInterval
to call the validation. I can't find a nice value for the delay; too short means a slow mouse click causes flicker, and too long means the validation seems unconnected to action which caused the blur.