Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript alert messages in infinite loop

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();">
like image 401
Rohit Sharma Avatar asked Jun 15 '11 10:06

Rohit Sharma


2 Answers

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); 
like image 196
Theopaul Kakkassery Avatar answered Sep 22 '22 02:09

Theopaul Kakkassery


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)

like image 38
James Wiseman Avatar answered Sep 21 '22 02:09

James Wiseman