UFO ET IT

Enter 키로 양식 제출 방지

ufoet 2020. 12. 29. 07:36
반응형

Enter 키로 양식 제출 방지


양식 자체에서 작동하는이 멋진 함수를 방금 작성했습니다.

$("#form").keypress(function(e) {
    if (e.which == 13) {
        var tagName = e.target.tagName.toLowerCase(); 
        if (tagName !== "textarea") {
            return false;
        }
    }
});

내 논리에서 텍스트 영역을 입력하는 동안 캐리지 리턴을 수락하고 싶습니다. 또한 입력 필드의 입력 키 동작을 다음 입력 필드로 탭하는 동작으로 대체하는 추가 보너스가 될 것입니다 (탭 키를 누른 것처럼). 누구든지 이벤트 전파 모델을 사용하여 해당 요소에서 Enter 키를 올바르게 실행하는 방법을 알고 있지만 언론에서 양식 제출을 방지합니까?


다음과 같은 입력에서 Enter 대신 탭 키 누르기를 모방 할 수 있습니다.

//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
        return false;
    }
});

Enter를 누를 때 다음 입력 에 초점을 맞추기 위해 어떤 선택기가 필요한지 분명히 알아야합니다 .


단일 입력 양식은 항상 Enter 키를 누를 때 제출됩니다. 이를 방지하는 유일한 방법은 다음과 같습니다.

<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>

여기 내 기능의 수정 된 버전이 있습니다. 다음을 수행합니다.

  1. 텍스트 영역, 단추, 제출 이외의 양식 요소에서 Enter 키가 작동하지 않도록합니다.
  2. Enter 키는 이제 탭처럼 작동합니다.
  3. preventDefault (), stopPropagation ()이 요소에서 호출되는 것은 좋지만 양식에서 호출하면 이벤트가 요소에 도달하는 것을 중지하는 것 같습니다.

따라서 내 해결 방법은 요소 유형을 확인하는 것입니다. 유형이 텍스트 영역 (입력 허용)이 아니거나 버튼 / 제출 (입력 = 클릭)이 아니면 다음 항목으로 이동합니다.

다른 요소가 단순한 형제가 아닐 수 있기 때문에 요소에서 .next ()를 호출하는 것은 유용하지 않습니다. 그러나 DOM은 선택시 순서를 거의 보장하므로 모두 괜찮습니다.

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
                if (this === e.target) {
                    focusNext = true;
                }
                else if (focusNext){
                    $(this).focus();
                    return false;
                }
            });

            return false;
        }
    }
}

사용성 관점에서 탭을 모방하도록 입력 동작을 변경하는 것은 매우 나쁜 생각입니다. 사용자는 양식을 제출하기 위해 Enter 키를 사용하는 데 익숙합니다. 그것이 인터넷이 작동하는 방식입니다. 이것을 깨서는 안됩니다.


기본 버튼으로 키 입력 게시물은 입력 키 누르기에 대한 기본 동작을 설정하는 방법을 설명합니다. 그러나 경우에 따라 Enter 키를 누를 때 양식 제출을 비활성화해야합니다. 완전히 막으려면 페이지 태그에 OnKeyPress 핸들러를 사용해야합니다.

<body OnKeyPress="return disableKeyPress(event)">

자바 스크립트 코드는 다음과 같아야합니다.

<script language="JavaScript">

function disableEnterKey(e)
{
     var key;      
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox      

     return (key != 13);
}

</script>

입력 필드에서 Enter 키를 눌렀을 때 양식 제출을 비활성화하려면 다음과 같이 입력 필드의 OnKeyPress 핸들러에서 위의 함수를 사용해야합니다.

<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">

출처 : http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx


Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.

By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.


In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.

$(document).on( 'keypress', '.input_class', function (e) {
    if (e.charCode==13) {
        $(this).parent('.container').children('.button_class').trigger('click');
        return false;
    }
});

In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.

Note that the input and the button have to be in the same container.


The previous solutions weren't working for me, but I did find a solution.

This waits for any keypress, test which match 13, and returns false if so.

in the <HEAD>

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.which == 13) && (node.type == "text")) {
    return false;
  }
}

document.onkeypress = stopRKey;

I prefer the solution of @Dmitriy Likhten, yet: it only worked when I changed the code a bit:

[...] else 
            { 
             if (focusNext){
                $(this).focus();
                return false; } //  
            }     

Otherwise the script didn't work. Using Firefox 48.0.2


I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.

$(document).ready(function () {
    $("#item-form").keypress(preventEnterSubmit);
});

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
                if (this === e.target) {
                    focusNext = true;
                } else {
                    if (focusNext) {
                        $(this).focus();
                        return false;
                    }
                }
            });

            return false;
        }
    }
}

ReferenceURL : https://stackoverflow.com/questions/1563062/prevent-form-submission-with-enter-key

반응형