ProgramingTip

jquery Enter 키를 활성화하고 이벤트를 탭으로 변경하는 방법

bestdevel 2020. 11. 4. 08:12
반응형

jquery Enter 키를 활성화하고 이벤트를 탭으로 변경하는 방법


jquery 솔루션을 원합니다. 가까워 야합니다. 무엇을해야합니까?

$('html').bind('keypress', function(e)
{
     if(e.keyCode == 13)
     {
         return e.keyCode = 9; //set event key to tab
     }
});

키를 누르는 것을 방지 할 수 있습니다. keyCode를 9로 변경하여 탭으로 만들 수 있지만 작동하지 않는 것입니다. 가까워 야 해 무슨 일이야?


해결책은 다음과 가변합니다.

$('input').on("keypress", function(e) {
            /* ENTER PRESSED*/
            if (e.keyCode == 13) {
                /* FOCUS ELEMENT */
                var inputs = $(this).parents("form").eq(0).find(":input");
                var idx = inputs.index(this);

                if (idx == inputs.length - 1) {
                    inputs[0].select()
                } else {
                    inputs[idx + 1].focus(); //  handles submit buttons
                    inputs[idx + 1].select();
                }
                return false;
            }
        });

이것은 완벽하게 작동합니다!

 $('input').keydown( function(e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if(key == 13) {
            e.preventDefault();
            var inputs = $(this).closest('form').find(':input:visible');
            inputs.eq( inputs.index(this)+ 1 ).focus();
        }
    });

이처럼 단순한 아닌 이유는 무엇입니까?

$(document).on('keypress', 'input', function(e) {

  if(e.keyCode == 13 && e.target.type !== 'submit') {
    e.preventDefault();
    return $(e.target).blur().focus();
  }

});

이렇게하면 이미 "제출"의 입력 유형에 증가를 맞추지 않는 한 위치로 바로 이동합니다. 이 또한 페이지에 동적으로 추가되는 입력에 작동합니다.

참고 : blur ()는 "on blur"이벤트 리스너가있는 모든 사람을 위해 focus () 될 가능성이 있습니다. 프로세스가 작동 할 필요는 없습니다.


PlusAsTab : 숫자 키패드 더하기 키를 탭 키에 해당하는 사용하는 jQuery입니다.

PlusAsTab 은이 시험에서와 같이 키를 사용하도록 구성 할 수도 있습니다 . 이 질문에 대한 나의 이전 답변 참조하십시오 .

귀하의 경우 Enter 키를 전체 페이지에 대한 탭 기능으로 대체하십시오 (옵션에서 키를 탭으로 설정 한 후).

<body data-plus-as-tab="true">
    ...
</body>

Ben의 플러그인에서 빌드이 버전은 select를 처리하며 allowSubmit에 대한 옵션을 사용할 수 있습니다. 즉. $("#form").enterAsTab({ 'allowSubmit': true});이렇게하면 버튼을 신청할 수있는 이벤트를 처리 할 수 ​​있습니다.

(function( $ ){
    $.fn.enterAsTab = function( options ) {  
    var settings = $.extend( {
       'allowSubmit': false
    }, options);
    this.find('input, select').live("keypress", {localSettings: settings}, function(event) {
        if (settings.allowSubmit) {
        var type = $(this).attr("type");
        if (type == "submit") {
            return true;
        } 
    }
    if (event.keyCode == 13 ) {
        var inputs =   $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])");
        var idx = inputs.index(this);
        if (idx == inputs.length - 1) {
           idx = -1;
       } else {
           inputs[idx + 1].focus(); // handles submit buttons
      }
        try {
            inputs[idx + 1].select();
            }
        catch(err) {
            // handle objects not offering select
            }
        return false;
    }
});
  return this;
};
})( jQuery );

나는 더 이상 생각하는 jQuery를 사용하여 들여진 답변의 코드를 작성했습니다. (지금부터, 즉시 및 읽기 전용 양식 요소를 무시합니다.)

$.fn.enterAsTab = function () {
  $(this).find('input').live("keypress", function(e) {
    /* ENTER PRESSED*/
    if (e.keyCode == 13) {
        /* FOCUS ELEMENT */
        var inputs =   $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])"),
            idx = inputs.index(this);

        if (idx == inputs.length - 1) {
            inputs[0].select()
        } else {
            inputs[idx + 1].focus(); // handles submit buttons
            inputs[idx + 1].select();
        }
        return false;
    }
  });
  return this;
};

이렇게하면 $ ( '# form-id'). enterAsTab (); ... 아직 아무도 그것을 그렇게하지 않았던 것입니다.


이것은 마침내 나를 위해 완벽하게 작동하는 것입니다. jqeasyui를 사용하고 잘 작동합니다.

$(document).on('keyup', 'input', function(e) {
 if(e.keyCode == 13 && e.target.type        !== 'submit') {
   var inputs =   $(e.target).parents("form").eq(0).find(":input:visible"),
   idx = inputs.index(e.target);
       if (idx == inputs.length - 1) {
          inputs[0].select()
       } else {
          inputs[idx + 1].focus();
          inputs[idx + 1].select();
       }
 }

});

내가 결정하는 것입니다.

$("[tabindex]").addClass("TabOnEnter");
$(document).on("keypress", ".TabOnEnter", function (e) {
 //Only do something when the user presses enter
     if (e.keyCode == 13) {
          var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
          console.log(this, nextElement);
           if (nextElement.length)
                nextElement.focus()
           else
                $('[tabindex="1"]').focus();
      }
});

의 tabindex에주의를 지불 하고 폼에 전체 페이지에 특정하지 않습니다.

노트 live 는 jQuery에 의해 폐기되었습니다.on


모든 유형의 입력 포함

$(':input').keydown(function (e) {
    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
    if (key == 13) {
        e.preventDefault();
        var inputs = $(this).closest('form').find(':input:visible:enabled');
        if ((inputs.length-1) == inputs.index(this))
            $(':input:enabled:visible:first').focus();
        else
            inputs.eq(inputs.index(this) + 1).focus();
    }
});

이 내 해결책을 환영합니다 .. :)

$('input').keydown( function (event) { //event==Keyevent
    if(event.which == 13) {
        var inputs = $(this).closest('form').find(':input:visible');
        inputs.eq( inputs.index(this)+ 1 ).focus();
        event.preventDefault(); //Disable standard Enterkey action
    }
    // event.preventDefault(); <- Disable all keys  action
});

위의 장점을 최대한 활용하여 양식 외부 등의 모든 입력에 대해 작업 할 수있는 기능을 추가했습니다. 또한 마지막 입력에 도달하면 지금 시작합니다. 입력이 하나 뿐인 경우에는 블러 처리 한 다음 단일 입력에 점점 더 맞춰 외부 블러 / 포커스를 트리거합니다.

$('input,select').keydown( function(e) {
  var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
  if(key == 13) {
    e.preventDefault();
    var inputs = $('#content').find(':input:visible');
    var nextinput = 0;
    if (inputs.index(this) < (inputs.length-1)) {
      nextinput = inputs.index(this)+1;
    }
    if (inputs.length==1) {
      $(this).blur().focus();
    } else {
      inputs.eq(nextinput).focus();
    }
  }
});


이 솔루션은 내 데이터 그리드에서 작동하지 않습니다. 나는 그들이 그러길 바랬다. 다음 입력, 열, 행 등으로 이동하기 위해 Tab 또는 Enter가 필요하지 않습니다. .focusout 또는 .change를 트리거하기 위해 Enter 만 필요하고 내 datagrid는 데이터베이스를 업데이트합니다. 그래서 나는 관련 텍스트 입력에 "입력"클래스를 추가하고 나를 위해 트릭을했다 :

$(function() {
   if ($.browser.mozilla) {
        $(".enter").keypress(checkForEnter);
    } else {
        $(".enter").keydown(checkForEnter);
    }
});

function checkForEnter(event) {
    if (event.keyCode == 13) {
        $(".enter").blur();
    }
}

$('input').live("keypress", function(e) {
            /* ENTER PRESSED*/
            if (e.keyCode == 13) {
                /* FOCUS ELEMENT */
                var inputs = $(this).parents("form").eq(0).find(":input:visible");
                var idx = inputs.index(this);

                if (idx == inputs.length - 1) {
                    inputs[0].select()
                } else {
                    inputs[idx + 1].focus(); //  handles submit buttons
                    inputs[idx + 1].select();
                }
                return false;
            }
        });

보이는 입력은 증가를 맞출 수 없습니다.


나는이 질문이 신보다 오래 예견되는 것이 좋습니다, 그렇게 우아한 대답은 본 적이 없습니다.

doc.on('keydown', 'input', function(e, ui) {
    if(e.keyCode === 13){
        e.preventDefault();
        $(this).nextAll('input:visible').eq(0).focus();
    }
});

인간적으로 가능한 한 단계 줄로 작업을 완료하는 것입니다.


통제 및 읽기 전용 요소를 모두 필터링해야합니다. 이 코드가 버튼을 가리면 안된다고 생각합니다.

$('body').on('keydown', 'input, select, textarea', function(e) {
    var self = $(this),
        form = self.parents('form:eq(0)'),
        submit = (self.attr('type') == 'submit' || self.attr('type') == 'button'),
        focusable,
        next;

    if (e.keyCode == 13 && !submit) {
        focusable = form.find('input,a,select,button,textarea').filter(':visible:not([readonly]):not([disabled])');
        next = focusable.eq(focusable.index(this)+1);

        if (next.length) {
            next.focus();
        } else {
            form.submit();
        }

        return false;
    }
});

저의 개발에 필요한 사항이 있었기 때문에 이에 대해 연구했습니다. 지난 이틀 동안 jQuery.tabNext () 플러그인과 같은 많은 기사를 읽고 솔루션을 시도했습니다.

IE11에 문제가 있습니다 (모든 IE 버전에는 버그가 있습니다). 입력 텍스트 다음에 비 텍스트 입력이 오면 선택이 지워지지 않습니다. 그래서 @Sarfraz 솔루션 제안을 기반으로 내 자신의 tabNext () 메서드를 만들었습니다. 나는 또한 그것이 어떻게 동작 해야하는지에 대해 생각하고 있었다 (현재 양식의 원만 또는 전체 문서를 통해). 가끔 사용하고 있기 때문에 대부분 tabindex 속성을 처리하지 않습니다. 나는 그것을 잊지 않을 것입니다.

내 기여가 모든 사람에게 쉽게 유용 할 수 있도록 여기에 jsfiddle 예제를 만들었습니다 https://jsfiddle.net/mkrivan/hohx4nes/

여기에 예제의 JavaScript 부분도 포함합니다.

            function clearSelection() {
            if (document.getSelection) { // for all new browsers (IE9+, Chrome, Firefox)
                document.getSelection().removeAllRanges();
                document.getSelection().addRange(document.createRange());
                console.log("document.getSelection");
            } else if (window.getSelection) { // equals with the document.getSelection (MSDN info)
                if (window.getSelection().removeAllRanges) {  // for all new browsers (IE9+, Chrome, Firefox)
                    window.getSelection().removeAllRanges();
                    window.getSelection().addRange(document.createRange());
                    console.log("window.getSelection.removeAllRanges");
                } else if (window.getSelection().empty) {  // maybe for old Chrome
                    window.getSelection().empty();
                    console.log("window.getSelection.empty");
                }
            } else if (document.selection) {  // IE8- deprecated
                document.selection.empty();
                console.log("document.selection.empty");
            }
        }
        function focusNextInputElement(node) { // instead of jQuery.tabNext();
            // TODO: take the tabindex into account if defined
            if (node !== null) {
                // stay in the current form
                var inputs = $(node).parents("form").eq(0).find(":input:visible:not([disabled]):not([readonly])");
                // if you want through the full document (as TAB key is working)
                // var inputs = $(document).find(":input:visible:not([disabled]):not([readonly])");
                var idx = inputs.index(node) + 1; // next input element index
                if (idx === inputs.length) { // at the end start with the first one
                    idx = 0;
                }
                var nextInputElement = inputs[idx];
                nextInputElement.focus(); //  handles submit buttons
                try { // if next input element does not support select()
                    nextInputElement.select();
                } catch (e) {
                }
            }
        }
        function tabNext() {
            var currentActiveNode = document.activeElement;
            clearSelection();
            focusNextInputElement(currentActiveNode);
        }
        function stopReturnKey(e) {
            var e = (e) ? e : ((event) ? event : null);
            if (e !== null) {
                var node = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
                if (node !== null) {
                    var requiredNode = $(node).is(':input')
                            // && !$(node).is(':input[button]')
                            // && !$(node).is(':input[type="submit"]')
                            && !$(node).is('textarea');
                    // console.log('event key code ' + e.keyCode + '; required node ' + requiredNode);
                    if ((e.keyCode === 13) && requiredNode) {
                        try {
                            tabNext();
                            // clearSelection();
                            // focusNextInputElement(node);
                            // jQuery.tabNext();
                            console.log("success");
                        } catch (e) {
                            console.log("error");
                        }
                        return false;
                    }
                }
            }
        }
        document.onkeydown = stopReturnKey;

내 생각을 따를 수 추가 주석 행도 남겼습니다.


나는 다소 오래 가지 않는다는 것을 선택하는 것 같다는 것입니다. 따라서 나는 나를 위해 작동하는 다음과 같이 수정했습니다. maxTabNumber는 탭 가능한 입력 필드의 최대 수를 보유하는 전역 변수입니다.

  $('input').on("keypress", function (e) {
                if (e.keyCode == 13) {
                    var inputs = $(this).parents("form").eq(0).find(":input");
                    var idx = inputs.index(this);

                    var tabIndex = parseInt($(this).attr("tabindex"));
                    tabIndex = (tabIndex + 1) % (maxTabNumber + 1);
                    if (tabIndex == 0) { tabIndex = 1; }
                    $('[tabindex=' + tabIndex + ']').focus();
                    $('[tabindex=' + tabIndex + ']').select();
          
                    return false;
                }
    });


다음은 Enter 키를 사용하거나 탭 키 (선택적 포함 포함)로 처리하는 jQuery 플러그인입니다.

$(document).ready(function() {
  $('#one').onEnter('tab');
  $('#two').onEnter('tab');
  $('#three').onEnter('tab');
  $('#four').onEnter('tab');
  $('#five').onEnter('tab');
});

/**
 * jQuery.onEnter.js
 * Written by: Jay Simons
 * Cloudulus.Media (https://code.cloudulus.media)
 */

if (window.jQuery) {
    (function ($) {
        $.fn.onEnter = function (opt1, opt2, opt3) {
            return this.on('keyup', function (e) {
                var me = $(this);
                var code = e.keyCode ? e.keyCode : e.which;
                if (code == 13) {
                    if (typeof opt1 == 'function')
                    {
                        opt1(me, opt2);
                        return true;
                    }else if (opt1 == 'tab')
                    {
                        var eles = $(document).find('input,select,textarea,button').filter(':visible:not(:disabled):not([readonly])');
                        var foundMe = false;
                        var next = null;
                        eles.each(function(){
                            if (!next){
                                if (foundMe) next = $(this);
                                if (JSON.stringify($(this)) == JSON.stringify(me)) foundMe = true;
                            }
                        });
                        next.focus();
                        if (typeof opt2 === 'function')
                        {
                            opt2(me, opt3);
                        }
                        return true;
                    }
                }
            }).on('keydown', function(e){
                var code = e.keyCode ? e.keyCode : e.which;
                if (code == 13)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
            });
        }
    })(jQuery);
} else {
    console.log("onEnter.js: This class requies jQuery > v3!");
}
input,
select,
textarea,
button {
  display: block;
  margin-bottom: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input id="one" type="text" placeholder="Input 1" />
  <input id="two" type="text" placeholder="Input 2" />

  <select id="four">
    <option selected>A Select Box</option>
    <option>Opt 1</option>
    <option>Opt 2</option>
  </select>
  <textarea id="five" placeholder="A textarea"></textarea>
  <input id="three" type="text" placeholder="Input 3" />
  <button>A Button</button>
</form>


IE를 사용하는 경우 저에게 저에게 딱 맞습니다.

    <body onkeydown="tabOnEnter()">
    <script type="text/javascript">
    //prevents the enter key from submitting the form, instead it tabs to the next field
    function tabOnEnter() {
        if (event.keyCode==13) 
        {
            event.keyCode=9; return event.keyCode 
        }
    }
    </script>

참고 URL : https://stackoverflow.com/questions/2335553/jquery-how-to-catch-enter-key-and-change-event-to-tab

반응형