What’s the best way to solve this kind of javascript dead loop?

Y

YouSui

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>
 
M

Matthias Reuter

YouSui said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,783
Latest member
RickeyDort

Latest Threads

Top