From: YouSui on
Hi guys,

Recently I'm maintaining a legacy project. I found one javascript dead
loop problem in a page. The demo code is as follows. When the user
clicks the first inputbox and type in 3 then directly click the second
input box, the dead loop occurs. Now my question is what's the best
way to solve or prevent this kind of problem? Great thanks.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>

<input type="text" name="a" id="a" value="" />
<input type="text" name="b" id="b" value="" />

<script type="text/javascript" charset="utf-8">
var a = document.getElementById("a");
a.onblur = function(){
if(a.value.length === 1){
alert("aaa");
a.focus();
a.select();
return false;
}
}

var b = document.getElementById("b");
b.onblur = function(){
if(b.value < a.value){
alert("bbb");
b.focus();
b.select();
return false;
}
}
</script>
</body>
</html>

From: Matthias Reuter on
YouSui wrote:

> Recently I'm maintaining a legacy project. I found one javascript dead
> loop problem in a page. The demo code is as follows. When the user
> clicks the first inputbox and type in 3 then directly click the second
> input box, the dead loop occurs. Now my question is what's the best
> way to solve or prevent this kind of problem? Great thanks.
>
> var a = document.getElementById("a");
> a.onblur = function(){
> if(a.value.length === 1){
> alert("aaa");
> a.focus();
> a.select();
> return false;
> }
> }
>
> var b = document.getElementById("b");
> b.onblur = function(){
> if(b.value < a.value){
> alert("bbb");
> b.focus();
> b.select();
> return false;
> }
> }

The best way to prevent this is to gracefully notify the user of mistakes.
Don't use an alert box but insert some text on the page. Then don't mess
with the user. If he focuses one element don't force the focus on a
different element.

I would recommend to validate user input on submit and not before. Imagine
in your example the user entered a valid value for a and some value for b,
which unfortunately is smaller than a. If now a is the wrong value and b
is correct (to the user), the only way to change the value of a is to
change b to a wrong value, then change a, and then change b again.

Matt