Forum Moderators: open

Message Too Old, No Replies

Can't seem to set focus dynamically

         

txbakers

10:13 pm on Feb 21, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



function chb(v){

  1. document.uform.check[v].checked = true;
  2. var scode = document.uform.check[v].value
  3. var fld = "distpaid" + scode;
  4. var nfield = eval("document.uform." + fld + ".value");
  5. var thefield = eval("document.uform." + fld);
  6. if (isNaN(nfield) ¦¦ nfield == ""){
  7. alert("Please enter only numbers");
  8. thefield.focus();
  9. }

}

This function checks to see that a certain text box, created dynamically, has a number as the value.

If it doesn't, we want to set the focus to that field, and it doesn't work.

we have tried to create the field name through javascript code as well using "thefield" as a variable.

We don't get an error message, neither do we get the focus. (see line 8)

Any ideas? THANKS.

rocknbil

3:18 am on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



eval should be used for evaluating numeric expressions, not concatenating strings. Did you try adding

alert(thefield.name);

to see if it's actually finding the object?
I would add an id to these objects and approach it this way, all you'd need to do is generate an ID as you generate the name:

document.write('<input type="text" name="'+somename+'" id="'+somename+'">');

With the exception of radio buttons, the id can be the same as the name.


function chb(v){
document.uform.check[v].checked = true;
var scode = document.uform.check[v].value;
var fld = "distpaid" + scode;
var thefield = document.getElementById(fld);
if (isNaN(theField.value) ¦¦ theField.value == ""){
alert("Please enter only numbers");
thefield.focus();
}
}

txbakers

11:42 am on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Good idea. I'll try that approach - thanks!

kaled

12:17 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As a general rule, I would set the focus PRIOR to the alert.

When the alert box closes, focus will be returned to the active control, however, the multi-threaded nature of browsers and operating systems means that there may be a race condition between you explicitly setting the focus and the focus being set by the closure of the alert box.

Kaled.

rocknbil

8:41 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How could I have missed that, DOH! Genius! :-) That is VERY important . . .

txbakers

6:16 pm on Feb 26, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



still not working.....

this is interesting though. When I directly call the field to focus:
document.uform.distpaid11.focus()

it will do it, if I'm NOT leaving that box.

If I'm testing that box, and tab away, it won't bring the focus BACK to that box.

What's with that?