The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> JavaScript onBlur event to maintain focus
digitalpurpose
post 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>
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Darin McGrew
post May 20 2011, 05:38 PM
Post #2


WDG Member
********

Group: Root Admin
Posts: 8,317
Joined: 4-August 06
From: Mountain View, CA
Member No.: 3



I've encountered forms that kept trying to move my input focus to wherever the site designer thought it should be. I ended up needing to close the tab to escape.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post May 20 2011, 06:32 PM
Post #3


.
********

Group: WDG Moderators
Posts: 8,253
Joined: 10-August 06
Member No.: 7



QUOTE(digitalpurpose @ May 20 2011, 10:38 PM) *

but the focus is moved to whichever element I was moving to which caused the onBlur event.

Isn't it the element you move from that causes the unblur event? And isn't that what you intended?

But note that this arrangement means the user can't leave the form if he doesn't want to finish it (except by closing the whole page, like Darin would tongue.gif ).

A more user-friendly solution might be to call the validation function with an onsubmit event in the FORM element, as described here: http://www.javascriptkit.com/javatutors/form6.shtml
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
digitalpurpose
post May 21 2011, 01:00 AM
Post #4


Novice
**

Group: Members
Posts: 27
Joined: 7-March 11
Member No.: 14,063



Currently, the focus is not being set to the email address field as I would like it to be.

Also, the only instance in which the case that Darin is highlighting could occur, is if the user began filling out the form, got to the email address field, and then decided not to continue filling out the form. Yes, adding this functionality would essentially keep the focus on the email address field, until an email address that passes the validation test is entered, however, since it is activated when the email address field enters a state of onBlur, it cannot be activated until the user puts their focus on the field, and then moves their focus to another field, and the focus will not be reset to the email address field unless they enter invalid input for the email address field.

I do not want to do validation onSubmit, because it has been requested that the form perform validation prior to being submitted.

Does anyone know of a way to use the onBlur event to set the focus on the input field that is processing the onBlur event?

I simply need to keep the focus on the email address field, once it gains focus via the user clicking or tabbing into the field, until they enter a valid email address.

I appreciate the recommendations, and understand that validating form data onSubmit is the norm, but in this particular case, a better fit would be the method I am trying to implement.

If there is no way to do this, I would be greatly surprised, but up until now, I have not been able to figure out how to manipulate the focus properly to produce the desired result.

This post has been edited by digitalpurpose: May 21 2011, 01:01 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post May 21 2011, 01:43 AM
Post #5


Jocular coder
********

Group: Members
Posts: 2,298
Joined: 31-August 06
Member No.: 43



QUOTE
I do not want to do validation onSubmit, because it has been requested that the form perform validation prior to being submitted.


Perhaps you are misunderstanding. Normally the above means validating the form using javascript onsubmit(); this happens before the form data is *submitted* to the server. Of course this can never be "forced", so you have to validate the data again on the server anyway.

The other interpretation is just crazy. (Or "power crazy"; or something) It is very antisocial to prevent forms from behaving in the way users expect them to.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post May 21 2011, 01:47 AM
Post #6


Jocular coder
********

Group: Members
Posts: 2,298
Joined: 31-August 06
Member No.: 43



Incidentally, a *sensible* form of onblur() feedback would be to add a red border or similar marker, alerting the user that this box is not yet OK.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
digitalpurpose
post May 21 2011, 04:40 AM
Post #7


Novice
**

Group: Members
Posts: 27
Joined: 7-March 11
Member No.: 14,063



QUOTE(Brian Chandler @ May 21 2011, 02:43 AM) *

QUOTE
I do not want to do validation onSubmit, because it has been requested that the form perform validation prior to being submitted.


Perhaps you are misunderstanding. Normally the above means validating the form using javascript onsubmit(); this happens before the form data is *submitted* to the server. Of course this can never be "forced", so you have to validate the data again on the server anyway.

The other interpretation is just crazy. (Or "power crazy"; or something) It is very antisocial to prevent forms from behaving in the way users expect them to.


Hi Brian thanks for your feedback.

I haven't misunderstood onSubmit ( or onsubmit(); ), perhaps the way I should have worded this is that I would like to validate the form data before the submit button is pressed.

I am not looking to make a form that is difficult to use, or unfamiliar. I simply want to reset the focus to the email address field if the user puts their focus on that field, and does not enter a valid email address. The email address field is the 3rd field in the form, so it cannot receive focus any other way except by the user clicking or tabbing into it, and once they have focused on that field, I want to perform a valid email address check with an onBlur event when they move to the next field, which if failed, will erase the contents of the email address field, and set the focus back on the email address field.

The current script I created does everything correctly except setting the focus, and my main question is, can the focus be set using an onBlur event to the same field which is calling the onBlur event. In other words, it seems to be that when focus is moved, which spurs the onBlur event, the script I wrote is processed, and then the focus is placed on the object which it was moving away to in the first place.

If this is the case, I am curious to know if there is some way to workaround this, and if there is not an already known workaround, I will post my final solution here once I finally figure one out. biggrin.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post May 21 2011, 05:31 AM
Post #8


Jocular coder
********

Group: Members
Posts: 2,298
Joined: 31-August 06
Member No.: 43



QUOTE
I am not looking to make a form that is difficult to use, or unfamiliar. I simply want to reset the focus to the email address field if the user puts their focus on that field, and does not enter a valid email address.


Forcing the focus to where you think it ought to be, instead of where the user wants to put it is a textbook case of making the form difficult to use. Actually you just provoke the skilled user into switching off javascript temporarily. Why do it?

Anyway, sorry, but I don't assist antisocial behaviour. But of course if you can move the focus, there is unlikely to be an arbitrary restriction to where you can put it.

I just checked the Firefox Javascript ("advanced") options, and realised I really don't want to allow any of the antisocial actions in the list. Ought to suggest that moving focus would be a good candidate to add, too.

User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post May 21 2011, 05:33 AM
Post #9


Jocular coder
********

Group: Members
Posts: 2,298
Joined: 31-August 06
Member No.: 43



QUOTE
... which if failed, will **erase** the contents of the email address field, and set the focus back on the email address field.


Oh crumbs. So if I mistype the '@' as '#', you want to delete want I've typed and make me start again. Time to hit the exit button.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post May 21 2011, 07:29 AM
Post #10


.
********

Group: WDG Moderators
Posts: 8,253
Joined: 10-August 06
Member No.: 7



QUOTE(digitalpurpose @ May 21 2011, 11:40 AM) *

The current script I created does everything correctly except setting the focus, and my main question is, can the focus be set using an onBlur event to the same field which is calling the onBlur event.

The focusing seems to be a problem in Firefox and (partially) Safari and Chrome, while my MSIE and Opera can focus correctly.

How about not using onblur, and instead validate the email field when any of the other form fields are focused? That way the user can leave the form if he wants to:

CODE
<form name="download-form">
<input type="text" name="Eml" id="Eml" value="">
<input type="text" name="foo" value="" onfocus="validateEmail();">
<input type="text" name="bar" value="" onfocus="validateEmail();">
</form>


But I think Brian's idea of adding a red border or similar is more user-friendly than erasing everything the user has already entered in the email field.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Darin McGrew
post May 21 2011, 10:12 AM
Post #11


WDG Member
********

Group: Root Admin
Posts: 8,317
Joined: 4-August 06
From: Mountain View, CA
Member No.: 3



QUOTE
I just checked the Firefox Javascript ("advanced") options, and realised I really don't want to allow any of the antisocial actions in the list. Ought to suggest that moving focus would be a good candidate to add, too.
That would be nice. All too frequently, the normal "space to page down" behavior is broken because the page thinks input focus belongs on their site search function.

Anyway, if you do email validation, then be sure to check the RFCs so you don't reject valid email addresses. For example, john-doe@example.com and john+doe@example.com are perfectly valid email addresses, but many systems reject them because of the hyphen or plus characters.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Brian Chandler
post May 21 2011, 10:25 AM
Post #12


Jocular coder
********

Group: Members
Posts: 2,298
Joined: 31-August 06
Member No.: 43



QUOTE
Anyway, if you do email validation, then be sure to check the RFCs so you don't reject valid email addresses.


Realistically, no-one does this. They find a regexp "somewhere" that is claimed to be 'valid email', and check against that. This one seems fairly simple, but even so the user-friendly thing to do is to state the rule(s) against which you are checking. "Email must include '@' and at least one point '.' after the @, followed by at least two characters in the last section of the domain name."

User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
digitalpurpose
post May 21 2011, 11:30 AM
Post #13


Novice
**

Group: Members
Posts: 27
Joined: 7-March 11
Member No.: 14,063



Thanks for all of the replies.

Christian J, your solution is similar to what I was considering doing as a workaround if it came to that, however, I don't want to call validateEmail() onFocus of all of the other fields, because then I feel I would be going the route of being, as Brian calls it, antisocial, lol, especially if the focus is put back to the email address field on a failed check of validateEmail().

Basically, the reason I want to do validation before the submit button is pressed, is that the form is in a lightbox, and upon successful submission, the user gets to download a free PDF file. Because the form / download are loaded in a lightbox, the user can't click the back arrow in their browser to repopulate the form with their previously entered data if they make a mistake, so I wanted to do the validation check for email first. The only required field is the email address, even though there are slots for their name, phone number, etc., etc., the only field required to qualify for the download is their email address.

One route I was thinking about would be to change the order of the form, and make the email address the first field. Give it focus using the onLoad() event, and then onBlur, instead of trying to move the focus back to it on a failed entry, simply reset the form. The only issue with that is, it's going even further down the antisocial route, if someone were to try to not fill out their email address first even though their prompt would be in the email field as soon as the lightbox loads.

I agree with a lot of the things being said about the "antisocial" behavior, but ultimately, this is a problem I am helping a friend with, and it's not my website to make a final decision, although I've already been over some of these points with them before I even posted the question here.

Silly JS focus, bah!
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post May 21 2011, 12:47 PM
Post #14


.
********

Group: WDG Moderators
Posts: 8,253
Joined: 10-August 06
Member No.: 7



QUOTE(digitalpurpose @ May 21 2011, 06:30 PM) *

Christian J, your solution is similar to what I was considering doing as a workaround if it came to that, however, I don't want to call validateEmail() onFocus of all of the other fields, because then I feel I would be going the route of being, as Brian calls it, antisocial, lol, especially if the focus is put back to the email address field on a failed check of validateEmail().

Not at all: if the user moves focus from one field to another he will not be able to tell if he invoked an unblur event in the first field or an onfocus event in the other one. In both cases your javascript will (try to) put the focus back on the email field, if it's considered invalid. The difference is that with onfocus the javascript does succeed in putting the focus on the email field, and as a bonus there won't be usability problems if the user tries to leave the form altogether. cool.gif

QUOTE
Basically, the reason I want to do validation before the submit button is pressed, is that the form is in a lightbox, and upon successful submission, the user gets to download a free PDF file. Because the form / download are loaded in a lightbox, the user can't click the back arrow in their browser to repopulate the form with their previously entered data if they make a mistake

That shouldn't be a problem with onsubmit and client-side javascript. The onsubmit event is invoked by trying to submit the form, but if the javascript returns false the form will not submit, and the user will still be on the form page.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Frederiek
post May 22 2011, 04:09 AM
Post #15


Programming Fanatic
********

Group: Members
Posts: 5,146
Joined: 23-August 06
From: Europe
Member No.: 9



Take a look here: http://www.xs4all.nl/~sbpoley/webmatters/formval.html .
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post May 23 2011, 06:46 PM
Post #16


.
********

Group: WDG Moderators
Posts: 8,253
Joined: 10-August 06
Member No.: 7



I should add that in my onclick solution above, no onclick is triggered if the email field is the last (or only one) the user fills in. To cover that you'd still need e.g. an onsubmit event.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
ChintooKhaade
post Sep 20 2011, 10:07 AM
Post #17





Group: Members
Posts: 1
Joined: 20-September 11
Member No.: 15,443



Hi Everyone,
In this demonstration we learn how to implement onblur event in java script. We know that onblur event trigger any java script method when specified control where onblur event is registered is losing the focuses. Mainly we can us onblur event to implement validation feature in control.... for more details check out the following link.........
http://mindstick.com/Articles/27987996-875...20Java%20Script


rolleyes.gif Thanks !!!!
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
chienline
post Oct 22 2012, 04:57 AM
Post #18





Group: Members
Posts: 1
Joined: 22-October 12
Member No.: 17,989



QUOTE(digitalpurpose @ May 21 2011, 03:38 AM) *

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>



Everything is cool in your code.
Just try to add onFocus event in "Eml"
CODE

onFocus='this.select();'


I'm also working on this kind of validation and couldn't find how to cancel onBlur event on the web.
Tried to copy the same validation function without alert message so that I can validate myTextBox on otherElement.onFocus event. But that means I have to attach that function on every elements I have.
Suddenly I found this simple working code.
Hope this helps many other Devs out there smile.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 8th December 2019 - 06:07 PM