テキストボックスの最後の文字の後にフォーカスを設定する 質問する

テキストボックスの最後の文字の後にフォーカスを設定する 質問する

電話番号用のテキスト ボックスが 3 つあります。ユーザーが入力すると、テキスト ボックスが次のテキスト ボックスへ自動的に移動します。ユーザーが Backspace キーを押すと、前のテキスト ボックスにフォーカスを移動できます。問題は、IE ではフォーカスがテキスト ボックスの先頭に設定されることです。これが私のコードです。Chrome では問題なく動作します。

$('#AreaCode').live('keyup', function (event) {
    if ($(this).val().length == $(this).attr("maxlength"))
        $('#Prefix').focus();
});

$('#Prefix').live('keyup', function (event) {
    if (event.keyCode == 8 && $(this).val().length == 0)
        $('#AreaCode').focus();

    if ($(this).val().length == $(this).attr("maxlength"))
        $('#Number').focus();
});

$('#Number').live('keyup', function (event) {
    if (event.keyCode == 8 && $(this).val().length == 0)
        $('#Prefix').focus();
});

後戻りするときにコンテンツの最後にフォーカスを設定するにはどうすればよいでしょうか?

ベストアンサー1

これは簡単な方法です。後戻りする場合は、$("#Prefix").val($("#Prefix").val());フォーカスを設定した後に追加するだけです

これはより適切な(よりクリーンな)方法です:

function SetCaretAtEnd(elem) {
        var elemLen = elem.value.length;
        // For IE Only
        if (document.selection) {
            // Set focus
            elem.focus();
            // Use IE Ranges
            var oSel = document.selection.createRange();
            // Reset position to 0 & then set at end
            oSel.moveStart('character', -elemLen);
            oSel.moveStart('character', elemLen);
            oSel.moveEnd('character', 0);
            oSel.select();
        }
        else if (elem.selectionStart || elem.selectionStart == '0') {
            // Firefox/Chrome
            elem.selectionStart = elemLen;
            elem.selectionEnd = elemLen;
            elem.focus();
        } // if
    } // SetCaretAtEnd()

おすすめ記事