如果没有所需的值,则将焦点对准文本框 [英] Focus back textbox on focus out if does not have required value

查看:105
本文介绍了如果没有所需的值,则将焦点对准文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文本框没有所需的值,我将重新聚焦。执行此功能后,文本框不会回聚。然而它正在警告( alert(必须是1); )。
$ b $

  $(#textbox)。blur(function(event){
if($(this) ();
event.preventDefault();
alert(Must is 1);
$(this).focus();
}
});

有什么想法?

解决方案


$ b

  $(#textbox)。blur(function(event) {
var tb = this;
if($(this).val()!=1){
event.preventDefault();
alert(Must be 1);
setTimeout(function(){$(tb).focus();},1);
}
});

通过将.focus()调用超时,可以使切换发生在单独的事件循环。还要注意,你试图得到不正确的值(.text),而且我必须保留对tb中元素的引用。



我怀疑这可能不适用于Safari。 Safari实际上并不愿意服从.focus()调用,它被alert()弄糊涂了。当然,如果您通过其他方式将消息传递给用户(请执行以下操作:-),那么可能会有效。


I am focusing back textbox if it does not have required values. Textbox is not focusing back after execution of this function. However it is alerting (alert("Must be 1");) correctly.

$("#textbox").blur(function(event){
       if ($(this).text != "1"){
          event.preventDefault();
          alert("Must be 1");
          $(this).focus(); 
        }
});

Any idea ?

解决方案

You could do this:

$("#textbox").blur(function(event){
       var tb = this;
       if ($(this).val() != "1"){
          event.preventDefault();
          alert("Must be 1");
          setTimeout( function() { $(tb).focus(); }, 1);
        }
});

By putting the ".focus()" call in a timeout, you make the switch happen in a separate event loop. Note also that you were trying to get the value incorrectly (".text"), and also that I have to preserve the reference to the element in "tb".

I suspect that this might not work in Safari. Safari is really reluctant to obey ".focus()" calls, and it gets confused by "alert()". Of course, if you deliver the message to the user by some other means (and please do so :-), then it might work.

这篇关于如果没有所需的值,则将焦点对准文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆