Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Canceling the focus change on the blur event

Status
Not open for further replies.

BobRodes

Instructor
May 28, 2003
4,215
US
I have some code that, when the user leaves an input box, checks for a valid date. If not, it sends an invalid date alert, wipes out the text, and resets the focus back to the box. Here's the code, after various simplifications:
Code:
    $('#startDate').on('blur', function (event) {
         if (!isDate(event.target.value)) { //isDate is a validation function, works fine
            alert('Invalid Date');
            event.target.value = '';
//           setTimeout(function () {  //the horror...the horror...
                document.getElementById(event.target.id).focus();
//           }, 1);
//            event.preventDefault;
//            event.stopImmediatePropagation;
//            event.stopPropagation;
            return false;
        }
    });
The browser (FF 9.0.1) apparently executes the focus() method, and then happily goes and focuses wherever the user had planned to go. I'm reduced to the frightful hack of pausing for a millisecond before executing the focus method so whatever thread is changing the focus can finish doing so, thereby allowing me to change it back.

I have attempted using the change event as well, but that doesn't work either. Since it fires before blur, that's not surprising. I've tried all of the three commands I've commented out, with no luck.

Can someone give me a glimpse under the hood?

An unforeseen consequence of the information revolution has been the exponential propagation of human error.
 
Update: I put a little test code together at home:
Code:
	$("#dob").blur(function (event) {
		if (event.target.value != ''){
			alert('Invalid date');
			document.getElementById('dob').focus();
		}
	});
This has the same problem in FF, and works fine in both Safari and IE.

An unforeseen consequence of the information revolution has been the exponential propagation of human error.
 
Update: I'm getting about as unenthusiastic about the blur, change, and focusout events as I was about the LostFocus event in VB6. I didn't know that it fired when you leave the browser window entirely, so I'm looking for other means to get what I want. Does anyone have any general insights to share about what to do and what not to do with validation? I generally prefer form-level validation, but in the case of an invalid date or whatever I prefer to try to stop the problem at the source.

An unforeseen consequence of the information revolution has been the exponential propagation of human error.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top