How do I set field focus using DOM?

D

donpro

Hi,

I have a form with date fields, I have created event listeners to
check for a validate when leaving the field (onblur). If invalid, I
need it to set the field back to the default value, select the field,
and return focus to the field. All is working except the focus. If
someone can point out the error in my code, it would be appreciated.

function validateDateEntered(e) {
var elementValue = getSrcElement(e);
if(!dateCheck(elementValue.value,'%MM/%DD/%YYYY') && !
isWhitespace(elementValue.value)) {
alert('Invalid Received date - format is MM/DD/YYYY and must be a
valid date');
elementValue.value=elementValue.defaultValue;
elementValue.select();
elementValue.focus();
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
}



function getSrcElement(e) {
elementClicked = 0;
if (window.event && window.event.srcElement) {
elementClicked = window.event.srcElement;
}
if (e && e.target) {
elementClicked = e.target;
}

return elementClicked;
}
 
R

RobG

Hi,

I have a form with date fields, I have created event listeners to
check for a validate when leaving the field (onblur). If invalid, I
need it to set the field back to the default value, select the field,
and return focus to the field.

That is a really unfriendly thing to do, it will cause your users
great frustration. If you want to validate onblur (it's better to use
the change event), just put something next to the field to let the
user know that the content is invalid and let them fix it themselves.

All is working except the focus. If
someone can point out the error in my code, it would be appreciated.

function validateDateEntered(e) {
var elementValue = getSrcElement(e);

As Randy said, that is not a good strategy for getting a reference to
the element that fired the event. Have the handler pass this to the
function and you have your reference without further hassle:

<input onclick="validateDateEntered(this);" ... >

and in your script:

function validateDateEntered(element) {
// element is a reference to the element that
// called the function
...
}


[...]
function getSrcElement(e) {
elementClicked = 0;
if (window.event && window.event.srcElement) {
elementClicked = window.event.srcElement;
}
if (e && e.target) {
elementClicked = e.target;
}
return elementClicked;
}

A simple version of that function would be:

function getSrcElement(e) {
e = e || window.event;
return e && (e.target || e.srcElement);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top