Programing

텍스트 상자에 Enter 키를 누르는 사용자를위한 JQuery 이벤트?

lottogame 2020. 4. 10. 08:03
반응형

텍스트 상자에 Enter 키를 누르는 사용자를위한 JQuery 이벤트?


Jquery에 사용자가 텍스트 상자의 Enter 버튼을 눌렀을 때만 트리거되는 이벤트가 있습니까? 또는 이것을 추가하기 위해 추가 할 수있는 플러그인이 있습니까? 그렇지 않다면 어떻게하면 빠른 플러그인을 작성합니까?


당신은 당신의 자신의 사용자 정의 이벤트를 연결할 수 있습니다

$('textarea').bind("enterKey",function(e){
   //do stuff here
});
$('textarea').keyup(function(e){
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

http://jsfiddle.net/x7HVQ/


   $('#textbox').on('keypress', function (e) {
         if(e.which === 13){

            //Disable textbox to prevent multiple submit
            $(this).attr("disabled", "disabled");

            //Do Stuff, submit, etc..

            //Enable the textbox again if needed.
            $(this).removeAttr("disabled");
         }
   });

여기 플러그인이 있습니다 : (Fiddle : http://jsfiddle.net/maniator/CjrJ7/ )

$.fn.pressEnter = function(fn) {  

    return this.each(function() {  
        $(this).bind('enterPress', fn);
        $(this).keyup(function(e){
            if(e.keyCode == 13)
            {
              $(this).trigger("enterPress");
            }
        })
    });  
 }; 

//use it:
$('textarea').pressEnter(function(){alert('here')})

여기 jquery 플러그인이 있습니다.

(function($) {
    $.fn.onEnter = function(func) {
        this.bind('keypress', function(e) {
            if (e.keyCode == 13) func.apply(this, [e]);    
        });               
        return this; 
     };
})(jQuery);

사용하려면 코드를 포함시키고 다음과 같이 설정하십시오.

$( function () {
    console.log($("input"));
    $("input").onEnter( function() {
        $(this).val("Enter key pressed");                
    });
});

여기에 jsfiddle http://jsfiddle.net/VrwgP/30/


해야 잘 지적 를 사용하는 것이 live()jQuery를에가되었습니다 되지 버전 이후 1.7및되었습니다 제거 jQuery를에 1.9. 대신 사용하는 on()것이 좋습니다.

다음과 같은 잠재적 인 문제를 해결하므로 다음과 같은 바인딩 방법론을 적극 권장합니다.

  1. 이벤트를에 바인딩하고 document.body$ selector를 두 번째 인수로 전달하면 on()리 바인딩 또는 이중 바인딩 이벤트를 처리하지 않고도 요소를 DOM에서 첨부, 분리, 추가 또는 제거 할 수 있습니다. 이벤트가 직접 연결되지 document.body않고 연결되어 있기 때문에 추가, 제거 및 다시 추가 할 수 있으며 이벤트에 바인딩 된 이벤트를로드하지 않습니다.$selector$selector
  2. off()before 를 호출 on()하면이 스크립트는 실수로 이중 바인딩 이벤트에 대해 걱정할 필요없이 페이지의 본문 또는 AJAX 호출의 본문 내에있을 수 있습니다.
  3. 내에 스크립트를 래핑하면 $(function() {...})이 스크립트를 페이지의 본문 또는 AJAX 호출의 본문에서 다시로드 할 수 있습니다. $(document).ready()AJAX 요청에 대해서는 발생 $(function() {...})하지 않습니다.

예를 들면 다음과 같습니다.

<!DOCTYPE html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        var $selector = $('textarea');

        // Prevent double-binding
        // (only a potential issue if script is loaded through AJAX)
        $(document.body).off('keyup', $selector);

        // Bind to keyup events on the $selector.
        $(document.body).on('keyup', $selector, function(event) {
          if(event.keyCode == 13) { // 13 = Enter Key
            alert('enter key pressed.');
          }
        });
      });
    </script>
  </head>
  <body>

  </body>
</html>

HTML 코드 :-

<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />      

<input type="button" id="btnclick">

자바 스크립트 코드

function AddKeyPress(e) { 
        // look for window.event in case event isn't passed in
        e = e || window.event;
        if (e.keyCode == 13) {
            document.getElementById('btnEmail').click();
            return false;
        }
        return true;
    }

양식에 기본 제출 버튼이 없습니다


입력이 search인 경우 on 'search'event 를 사용할 수도 있습니다 .

<input type="search" placeholder="Search" id="searchTextBox">

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

또 다른 미묘한 변형. 나는 약간의 힘을 분리하여 갔으므로 enter 키를 잡을 수있는 플러그인이 있고 이벤트에 정상적으로 바인딩합니다.

(function($) { $.fn.catchEnter = function(sel) {  
    return this.each(function() { 
        $(this).on('keyup',sel,function(e){
            if(e.keyCode == 13)
              $(this).trigger("enterkey");
        })
    });  
};
})(jQuery);

그리고 사용 중 :

$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });

이 변형을 통해 이벤트 위임을 사용할 수 있습니다 (아직 생성하지 않은 요소에 바인딩).

$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });

keypressjQuery 문서를 읽을 때까지 enter 버튼으로 이벤트를 시작 하지 못하고 얼마 동안 내 머리를 긁었습니다.

" 키 입력 이벤트는 브라우저가 키보드 입력을 등록 할 때 요소로 전송됩니다. 이는 키 다운 이벤트가 아닌 Shift 키, Esc 및 삭제 트리거 키 다운 이벤트와 같은 수정 자 및 비 인쇄 키를 제외하고 키 다운 이벤트와 유사합니다. "( https://api.jquery.com/keypress/ )

엔터 버튼을 누르기 위해 keyup또는 keydown이벤트 를 사용해야했습니다 .

참고 URL : https://stackoverflow.com/questions/6524288/jquery-event-for-user-pressing-enter-in-a-textbox

반응형