简体   繁体   中英

setting focus following validation of field with onblur not working

After spending an hour or more looking for some alternative, I'm coming up empty. Upon losing focus, a function is called, the portion to set focus back to the calling field upon validation fail is not working...

example here: http://owenparker.com/test/testval.php

 var emptyString = /^$/; function validatePresent(valfield, infofield) { var stat = commonCheck(valfield, infofield, true); if (stat != proceed) return stat; msg(infofield, "warn", ""); return true; } var proceed = 2; function commonCheck(valfield, infofield, required) { if (!document.getElementById) return true; // not available on this browser - leave validation to the server var infoelem = document.getElementById(infofield); if (!infoelem.firstChild) return true; if (infoelem.firstChild.nodeType != Node.TEXT_NODE) return true; if (emptyString.test(valfield.value)) { if (required) { msg(infofield, "error", "ERROR: required"); setfocus(valfield); return false; } else { msg(infofield, "warn", ""); // OK return true; } } return proceed; } function msg(fld, msgtype, message) { var dispmessage; if (emptyString.test(message)) dispmessage = String.fromCharCode(160); else dispmessage = message; var elem = document.getElementById(fld); elem.firstChild.nodeValue = dispmessage; elem.className = msgtype; } function setFocusDelayed() { global_valfield.focus(); } function setfocus(valfield) { // save valfield in global variable so value retained when routine exits global_valfield = valfield; setTimeout( 'setFocusDelayed()', 100 ); } 
 <table border=0 width=500px> <tr> <td>Misc 1:&nbsp; <input name="misc1" id="misc1" type="text" size="10" tabindex=1 autofocus onblur="validatePresent(this, 'inf_misc1');"> <div id="inf_misc1">&nbsp;</div> </td> </tr> <tr> <td>Whatever:&nbsp; <select name="whatever" id="whatever" tabindex=2 onblur="validatePresent(this, 'inf_whatever');"> <option value="" SELECTED>Choose</option> <option value="OPT1">Option 1</option> <option value="OPT2">Option 2</option> </select> <div id="inf_whatever">&nbsp;</div> </td> </tr> </table> 

Try this:

function setfocus(valfield)
{

  setTimeout( function () {
      valfield.focus();
  }, 100 );
}

passing a closure to setTimeout w/o using a global variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM