Focus Form

D

DonO

Not sure why this isn't working. I'm building a function to check the
value of a form field to make sure it's numeric or a comma or period.
I know this could probably be done with a regex function, but that's
not my strong suit...

The part I don't understand is when it throws the error that the field
doesn't match the criteria, it fails to put the focus on the field. It
highlights it, but focus goes to the next text box.

Thanks,
D.

<script type="text/javascript">
function check_numeric(inObj){
var allowedChars = "1234567890,.";
var checkStr = inObj;

var curChar = '';
var chkChar = '';
var isNumber = 1;

for(i=0; i<checkStr.value.length; i++){
curChar = checkStr.value.charAt(i);
for (j = 0; j < allowedChars.length; j++){
if (allowedChars.charAt(j) == curChar) break;
if (j == (allowedChars.length-1)) isNumber = 0;
}
if(isNumber == 0){
alert('Only the following characters are allowed:\n
\n'+allowedChars);
document.getElementById
(inObj.id).style.background="#f99";
inObj.focus(); // not working
break;
}
}
if(isNumber == 1){
document.getElementById(inObj.id).style.background="#fff";
}
}
</script>
 
A

Asen Bozhilov

Not sure why this isn't working. I'm building a function to check the
value of a form field to make sure it's numeric or a comma or period.
I know this could probably be done with a regex function, but that's
not my strong suit...

Something like this one?

Code:
function isNumeric(input_id)
{
var arr = document.getElementById(input_id).value.split(','),
curr;
for (var i = 0, len = arr.length; i < len; i++)
{
curr = arr[i];
if (Number(curr) != curr || /^\s*$/.test(curr))
{
return false;
}
}
return arr.length;
}

See that expression:
Number(curr) != curr

Internaly that will be looks:
Number(curr) != ToNumber(curr)
11.9.3 The Abstract Equality Comparison Algorithm in ECMA 3

The real benefit of that technique is NaN. Because comparison any NaN
value results will be false. See 8.5 The Number Type from ECMA 3

Regards.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top