简体   繁体   中英

javascript focus() not working, nor setting field value

Notes Domino web form, validating onblur what was entered in a field. Field is set as a number but I want to catch what was entered immediately if it is not a number. Then I want to clear what was entered and put the focus right back in the field. I get the code to run, and the alert comes up correctly but the focus does not happen, nor does the value get removed.

function checkNumeric(fld, nm) {
    debugger;
      var x;
      x = document.getElementById(fld).value;
      // If x is Not a Number or less than one or greater than 10
      if (isNaN(x)) {       
        document.getElementById(fld).value = '';
        alert("Non-numeric entry of '" + x + "' in : " + nm +", please try again.");
        document.getElementById(fld).focus();
      }       
    }

Be also sure that the event handler which calls this is set to prevent default. Otherwise it might be the element get the focus but is removed afterwards by the event handler emediatly.

            function checkNumeric(fld, nm) {
            //debugger;
            var x;
            if (typeof fld !== "string") {
                alert("fld is not a string");
            }
            if (typeof nm !== "string") {
                alert("nm is not a string");
            }

            var elm = document.getElementById(fld);
            if (elm) {
                x = elm.value;
                if (isNaN(x)) {
                    elm.value = '';
                    alert("Non-numeric entry of '" + x + "' in : " + nm + ", please try again.");
                    elm.focus();
                }
            }
        }

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