Alert boxes in infinite loop, here I am trying to put a popup alert message on 2 consecutive fields so they cannot be left blank, I know why it is happening - because when onblur event of 1st function is launched it gives focus to second one & when it jumps back to first one onblur of 2nd textfield is launched.
I know validation would be best when done at the form level, but this is the requirement I got.
Any help?
Javascript code
function x()
{
if( document.getElementById("1").value.length==0)
{
alert('1 is required');
document.getElementById("1").focus();
}
}
function y()
{
if(document.getElementById("2").value.length==0)
{
alert('2 is required');
document.getElementById("2").focus();
}
}
HTML code
<input type="text" name="City Name" id="1" onblur="javascript:x();">
<input type="text" name="Kitty Name" id="2" onblur="javascript:y();">
Instead of handling it in onblur()
event, you can handle it in onchange()
event.
If you still want to use onblur()
, then use the focus inside setTimeout
as shown below.
alert('2 is required');
setTimeout(function() { document.getElementById("2").focus(); }, 100);
There is a fundamental problem when trying to refocus on a field on an onblur
when it is invalid. If the user decides to navigate away, the simply can't. When they click away from the field, they are forcibly taken back. I have seen instances where a user is forced to kill their browser session, just to escape an over-zealous onblur
validation.
I realise this might not be the exact solution you are after, but can I recommend another approach that still involves client-side validation.
I recommend you highlight the field as being invalid in some way on the onblur
. E.g. put a star next to it, highlight it red, etc. This way you can dispense with the alert
and user still has control.
When the user comes to submit the form, you perform your client-side checks and display alert to them then (see @Phill Sacre's answer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With