JavaScript-在警报消息之后设置焦点



当验证失败时,我会尝试专注于同一元素。这是我的HTML代码:

<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate('potatoes')" autocomplete='off'>

这是我的JavaScript代码:

function Validate(id) {
var errors = {
    potatoes : 'enter potatoes',
    hamburgers : 'enter'
};
if (document.getElementById(id).value === '') {
    if (id in errors) {
        alert(errors[id]);
         //setTimeout(function(){document.getElementById(id).focus();}, 1);
    }
} 

}

我尝试使用.focus()方法设置焦点,但它不起作用。我读到,当我调用函数Validate()时,这可能取决于HTML中的" Onblur",所以我尝试更改它,但是到目前为止什么都没有。

这里有一个问题。此代码正在循环。当触发"焦点"时,再次调用函数验证,显示另一个警报对话框。

那是一个工作代码

html

<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate(this)" autocomplete='off'>

javascript

var validating = false; //<-- IMPORTANT
function Validate(element) {
var id = element.id;
var errors = {
    potatoes : 'enter potatoes',
    hamburgers : 'enter'
};
if (document.getElementById(id).value === '') {
    if (id in errors) {
            if(validating == false) {
                    validating = true
            alert(errors[id]);
            setTimeout(function(){
                document.getElementById(id).focus();
                validating = false;
            }, 1);
            }
    }
}
} 

在html中,我正在通过 this ,这样做是通过元素,在验证函数中,您可以访问ID,只需调用

var id = element.id;

对于焦点问题(由循环问题引起),您可以看到我正在使用验证变量,以了解何时验证何时何时进行验证。这让验证函数避免循环进行。所以:

1)定义a 验证 var 外部 validate函数并将其设置为false。

2)触发 focus nerver 仅当验证是错误的,然后将其设置为 true

JavaScript函数alert(string)是同步的。当用户对警报消息做出反应时,该脚本被暂停。无需做一些特别的事情。以下片段应起作用:

alert(errors[id]);
document.getElementById(id).focus();

用户提交了警报消息后,该元素直接得到焦点。

您可以使用这样的jQuery:

setTimeout(function() {$('#yourInputId').focus();},1);

最新更新