使用jQuery将焦点设置为错误值的输入字段

时间:2016-01-24 14:38:05

标签: jquery validation input focus

我有一个HTML:

<div id="div1">
  <input name="inText" type="text" id="input1" />
  <input name="inText" type="text" id="input2" />
</div>

我想强制用户只输入以“a”开头的文本,所以我使用这个jQuery脚本:

$("#div1 input").blur(function (){
    var re = /^a/;
    if ( $(this).val() != "" && ! re.test($(this).val()) ) {
        alert('The text must begin with "a"');
        $(this).focus();
    }
});

但是,我无法将焦点/选择重新输入错误的输入。如果您使用TAB键或单击下一个输入,则光标始终会在那里但不会返回。

我也试过这个,但也没有成功:

var currentInput;

$("#div1 input").focusout(function (){
    var re = /^a/;
    if ( $(this).val() != "" && ! re.test($(this).val()) ) {
        alert('The text must start with "a"');
        currentInput.focus();
        currentInput.select();
    }
});

$("#div1 input").focusin(function (){
    currentInput = $(this);
});

事件change也无法正常工作。有什么想法可以解决这个问题吗?

经过额外测试后,它似乎在MS Internet Explorer中按预期工作,但在Firefox(版本43)中没有。在Firefox和其他主要浏览器中使用的任何想法?

0 个答案:

没有答案