【问题标题】:jquery - How to return focus to the same textboxjquery - 如何将焦点返回到同一个文本框
【发布时间】:2013-02-22 05:37:52
【问题描述】:

我有 2 个文本框。如果第一个文本框是空的,当我点击选项卡时它不能继续到第二个文本框,否则用户会故意将焦点放在第二个文本框上。

html

<input type="text" id="txt1" />
<input type="text" id="txt2" />

jquery/javascript

$("#txt1").keydown(function (e) {
    if (e.which == 9)  {
        if ($.trim($(this).val() == ""))
            $(this).focus();
     }
 });

if ($("#txt2").is(":focus")) {
    if ($.trim($("#txt1").val() == "")) 
         $("#txt1").focus();
}

请看这个:http://jsfiddle.net/N8GAr/

我需要这方面的帮助。谢谢。

【问题讨论】:

  • 不确定您为什么要这样做。但我建议禁用第二个输入,否则它会让您的用户感到困惑。

标签: jquery textbox


【解决方案1】:

像这样使用jquery的focus()函数

$("#txt2").focus(function() {
        alert('abc');
        if ($.trim($("#txt1").val() == "")) 
             $("#txt1").focus();
    });

只需在Jsfiddle.net 上查看您想要的结果

【讨论】:

    【解决方案2】:

    试试这个

    $("#txt1").keydown(function (e) { 
    if (e.which == 9)  {
        if ($.trim($(this).val() == ""))
            $(this).focus();
    }
    });
    $("#txt2").focus(function(){
        if ($.trim($("#txt1").val() == "")) 
            $("#txt1").focus();
    });
    

    【讨论】:

      【解决方案3】:

      请在下面找到解决方案:

      $(document).ready(function() {
          $("#txt2").focus(function(){
              if(!$("#txt1").val())
              $("#txt1").focus();
          });
      });
      

      【讨论】:

        【解决方案4】:

        您不需要在那里进行双重逻辑检查。例如,如果第一个字段为空,则此代码将不允许第二个字段聚焦。你想要这个,对吧? 如果用户在第一个字段中按下制表符,它仍将保持第一个字段为焦点。如果第一个字段不为空,则只会移动到第二个字段。

        $("#txt2").focus(function(e){
            if (!$.trim($("#txt1").val())) {
               $("#txt1").focus();
               return false;
            }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-20
          • 1970-01-01
          • 2018-07-18
          相关资源
          最近更新 更多