2012-05-10 13 views
18

하나씩 숫자가 4 개인 입력이 있습니다. 내가 원하는 것은 숫자가 설정되면 자동으로 다음 입력으로 포커스를 설정하는 것입니다. 그들은 모두 클래스 "입력"을 가지고 있습니다. 다음 입력에 초점을 맞 춥니 다. (jquery)

이것은 꽤 작업했다 :

$(".inputs").keydown(function() { 

      $(this).next().focus(); 
     }); 
+0

이 게시물을 참조 [1]에 적응 주시기 바랍니다/1232379/focus-to-the-next-input-in-jquery – BinBin

+0

몇 가지 새로운 기능에 대해서는 [updated post] (http://stackoverflow.com/a/10539258/297641)를 참조하십시오. autotab' [DEMO] (http://jsfiddle.net/skram/qygB2/4/) –

답변

38

에 참조하고 maxlength은 동일합니다.

DEMO

$(".inputs").keyup(function() { 
    if (this.value.length == this.maxLength) { 
     $(this).next('.inputs').focus(); 
    } 
}); 

편집 :에서는 다음과 같은 사항에 대해 약간의 시간 소비 (완전히 테스트되지 만, 기본 테스트가 잘 작동)

1. Allowing just numeric chars 
    2. Allow some control like del, backspace, e.t.c 
    3. Backspace on empty textbox will move to prev textbox 
    4. charLimit var to dynamically decide how many char you want to restrict. 

코드 :

$(function() { 
    var charLimit = 1; 
    $(".inputs").keydown(function(e) { 

     var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145]; 

     if (e.which == 8 && this.value.length == 0) { 
      $(this).prev('.inputs').focus(); 
     } else if ($.inArray(e.which, keys) >= 0) { 
      return true; 
     } else if (this.value.length >= charLimit) { 
      $(this).next('.inputs').focus(); 
      return false; 
     } else if (e.shiftKey || e.which <= 48 || e.which >= 58) { 
      return false; 
     } 
    }).keyup (function() { 
     if (this.value.length >= charLimit) { 
      $(this).next('.inputs').focus(); 
      return false; 
     } 
    }); 
}); 

DEMO

+1

+1 나는이 아이디어가 마음에 든다. – Jivings

+0

나도. Brilliant :) – domino

+2

와우 아주 훌륭합니다. click()과 결합하여 사용자가 이미 채워진 텍스트 상자를 선택할 때 값을 재설정합니다. 현재 사용자가 채워진 입력을 선택하고 숫자를 입력하면 다음 입력이 아닌 다음 입력에 집중합니다 (모든 텍스트 상자가 채워 졌다고 가정). 이상적인 시나리오에서는 새 번호를 입력하기 전에 번호를 삭제하지 않아도됩니다 (자동으로 바꿉니다). 나는 이것이 어떻게 1 개 이상의 char 한도로 구현하는 것이 문제가되는지 알 수있다. 그냥 내 생각. 클릭()은 나를 위해 트릭을 어쨌든 할 것입니다 :) – domino

4

바로 다음 요소를 얻을 것이다, 그것은 무엇이든. 당신은 아마도 원할 것입니다 :

$(".inputs").keyup(function() { 
    $(this).next(".inputs").focus(); 
}); 

또한 키 입력은 올라가지 않거나 너무 빨리 변경됩니다.

+0

아, 네. keyup 함수가 delete/backspace 키를 어떻게 든 무시할 수 있습니까? – domino

+0

@domino 가능합니다. 내 게시물을 수정하겠습니다. – Jivings

+0

실제로 문제를 일으킬 수있는 탭 키 등의 다른 키가 많이 있습니다. 가장 쉬운 방법은 숫자 만 필터링하는 것입니까? – domino

0

keyup을 사용하십시오.

$(".inputs").keyup(function() { 
    $(this).next().focus(); 
});​ 

내가 각 텍스트 상자에 1로 최대 길이를 설정 제안하고 val.length 번 다음 단계로 전환 할 행동 http://jsfiddle.net/qygB2/

0

최신 jQuery 버전을 사용하는 경우 on 메서드를 사용하는 것이 좋습니다. 당신이 jQuery를 소스 코드로 이동하는 경우, 당신은 다른 모든 이벤트 방법이 지금은이 방법에 재 것을 알 수 있습니다, 왜 직접 사용하지 마십시오

$(document).ready(function() { 
     $('.inputs').on('keyup', function(){ 
      $(this).next().focus(); 
     }) 
}); 
1

를 검색하고 난에 결국 개발 후

자바 스크립트 (JQuery와) :

var codeCharInput = 'input.code-char'; 
$(codeCharInput+':first').focus(); 
$(codeCharInput).keyup(function(e) { 
    if ((e.which == 8 || e.which == 46)) { 
    $(this).prev(codeCharInput).focus().val($(this).prev().val()); 
    } else { 
    if (this.value.length == this.maxLength) { 
     $(this).next(codeCharInput).focus(); 
    } 
    } 
}); 
것을 가능하게 crossbrowser 조각은 백 스페이스 버튼을 통해 다시 초점을 맞출 수있는 능력과도 같은 클래스 (1 개 문자로 테스트) 최대 길이에 따라와 다음 입력 필드의 초점을 맞 춥니 다

HTML :

<input type="text" name="chars[]" maxlength="1" class="code-char" /> 
<input type="text" name="chars[]" maxlength="1" class="code-char" /> 
<input type="text" name="chars[]" maxlength="1" class="code-char" /> 
<input type="text" name="chars[]" maxlength="1" class="code-char" /> 
0

클래스 또는 ID의 이름을 지정하지 않고 next를 사용하면 텍스트 상자에 계속 초점을 맞 춥니 다. @에

$(this).hide();   
$(this).next().show(); 
$('input[type=text]').focus(); 
0

건물 베가의 대답

inputs.keydown(function(e) { 
    var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145]; 

    $(this).val(''); 

    if (e.which == 8 && this.value.length == 0) { 
     $(this).prev(inputs).focus(); 
    } else if ($.inArray(e.which, keys) >= 0) { 
     return true; 
    } else if (this.value.length > charLimit) { 
     $(this).next(inputs).focus(); 
     return false; 
    } else if (e.shiftKey || e.which <= 48 || e.which >= 58) { 
     return false; 
    } 
}).keyup (function() { 
    if (this.value.length >= charLimit && $(this).next(inputs).attr('type') === 'text') { 
     $(this).next(inputs).focus(); 
     return false; 
    } 
}); 

사용자가 이미 대신 다음 입력에가는, 그것은 우선합니다 값을 가지고 입력을 클릭하면, 그것은 또한 단지에 초점을 맞출 것이다 텍스트 입력. 나는 텍스트 입력 옆에 제출 입력이 있었고 백 스페이스를 사용하여 실수로 페이지를 리디렉션 할 수있는 상황이있었습니다.

1

다음은 Enter 키를 누르거나 shift + Enter를 누를 때 이전 요소에 초점을 맞출 때 다음 요소로 포커스를 이동하는 데 사용되는 enter 키를 만들기 위해 사용하는 코드입니다. 기본적으로

1) :

tabables = $("*[tabindex != '-1']:visible"); 
var index = tabables.index(element); 
tabables.eq(index + 1).focus(); 

2) 여기서 마음 fordward 뒤로하고 유효한 포커스를 요소에 가지는 동작을 캡슐화하는 "클래스"입니다. http://stackoverflow.com/questions :

가 나는 데 도움이 몇 가지 코드가 사용자의 요구에 맞는 경우, 사용자의 요구 :

EnterAsTab = function() { 
    this.ENTER_KEY = 13; 
}; 

EnterAsTab.prototype.init = function() { 
    this.listenOnEnterKey(); 
}; 

EnterAsTab.prototype.listenOnEnterKey = function() { 

    var me = this; 
    $('form input').on('keypress', function (event) { 

      if (event.which === me.ENTER_KEY) { 

       if (!event.shiftKey) 
        me.findNextFocusableElement(this); 
       else 
        me.findPreviousFocusableElement(this); 

       event.preventDefault(); 
      } 
     } 
    ); 
}; 

EnterAsTab.prototype.findNextFocusableElement = function (element) { 
    this.findFocusableElement(element, this.increaseIndex); 
}; 

EnterAsTab.prototype.findPreviousFocusableElement = function (element) { 
    this.findFocusableElement(element, this.decreaseIndex); 
}; 

EnterAsTab.prototype.findFocusableElement = function (element, callable) { 

    var tabables = $("*[tabindex != '-1']:visible"); 
    var index = tabables.index(element); 
    var counter = 1; 
    var nextElement = undefined; 

    try { 

     while (true) { 

      if ((nextElement = tabables.eq(index + counter)).length === 0) { 
       break; 
      } 

      if (this.isFocusableElement(nextElement)) { 

       var newIndex = callable.call(this, index, counter); 
       tabables.eq(newIndex).focus(); 

       break; 
      } else { 
       counter++; 
      } 
     } 
    } catch (error) { 
     console.log(error); 
    } 

}; 

EnterAsTab.prototype.increaseIndex = function (index, counter) { 
    return (index + counter); 
}; 

EnterAsTab.prototype.decreaseIndex = function (index, counter) { 
    return index - counter; 
}; 

EnterAsTab.prototype.isFocusableElement = function (element) { 

    return ['SELECT', 'TEXTAREA'].indexOf(element.prop('tagName')) > -1 || 
     element.is(':text') || 
     element.is(':checkbox') || 
     element.is(':radio'); 
}; 

var enterAsTab = new EnterAsTab(); 
enterAsTab.init(); 
관련 문제