JavaScript onBlur event to maintain focus |
JavaScript onBlur event to maintain focus |
digitalpurpose |
May 20 2011, 03:38 PM
Post
#1
|
Novice Group: Members Posts: 27 Joined: 7-March 11 Member No.: 14,063 |
Hello Everyone,
I'm trying to add some eMail validation to a form. Basically, I am using an onBlur event on the email address field to check that the email is valid, and if not, to show an alert, empty the field, and restore focus to the email address field. I am running into a problem, which is that when I move focus away from the email address field when an invalid address is entered, the alert is shown, the text is removed, but the focus is moved to whichever element I was moving to which caused the onBlur event. I am thinking that I cannot set the focus to a field using an onBlur event from that field, but perhaps I am wrong. The form's name is download-form, and the name and ID of the email address field is Eml. I am using the event onBlur="validateEmail();" on the email address input field, the code of validateEmail() is below. Any help would be appreciated! CODE <script> function validateEmail() { var x=document.forms["download-form"]["Eml"].value; var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Please Enter a Valid eMail Address"); document.forms["download-form"]["Eml"].value = ""; document.getElementById("Eml").focus(); } } </script> |
Lo-Fi Version | Time is now: 24th April 2024 - 08:11 PM |