JavaScript focus() 不起作用,也没有设置字段值



Notes Domino Web 表单,验证在字段中输入的内容。 字段设置为数字,但如果不是数字,我想立即捕获输入的内容。 然后我想清除输入的内容并将焦点放回现场。 我让代码运行,警报正确出现,但焦点没有发生,值也没有被删除。

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();
      }       
    }

还要确保调用 this 的事件处理程序设置为阻止默认值。否则,它可能是元素获得焦点,但随后被事件处理程序临时删除。

            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();
                }
            }
        }

最新更新