programing

jquery 비활성화 양식 제출시

new-time 2020. 5. 10. 12:01
반응형

jquery 비활성화 양식 제출시


내 페이지에 다음과 같은 자바 스크립트가 있는데 작동하지 않는 것 같습니다.

$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});

입력시 양식 제출을 비활성화하거나 더 나은 방법으로 아약스 양식 제출을 호출하고 싶습니다. 어느 솔루션이든 허용되지만 위의 코드로 양식을 제출할 수 없습니다.


경우

keyCode

적발되지 않으며, 캐치

which

:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

편집 : 그것을 놓쳤다,

keyup

대신에 사용하는 것이 좋습니다

keypress

편집 2 : 일부 최신 버전의 Firefox에서와 같이 양식 제출이 방지되지 않으므로 키 누르기 이벤트를 양식에 추가하는 것이 더 안전합니다. 또한 이벤트를 "name"양식에 바인딩하고 양식 ID에만 바인딩하면 작동하지 않습니다 (더 이상?). 따라서 코드 예제를 적절하게 변경하여 더 명확하게 만들었습니다.편집 3 : 변경

bind()

on()


일반적

Enter

으로 입력 요소에 중점을두면 양식이 제출됩니다 .양식 내의 입력 요소에서

Enter

키 (code

13

)를 비활성화 할 수 있습니다 .

$('form input').on('keypress', function(e) {
    return e.which !== 13;
});

데모 : http://jsfiddle.net/bnx96/325/


더 짧은 :

$('myform').submit(function() {
  return false;
});

$('form').keyup(function(e) {
  return e.which !== 13  
});

event.which

속성은 event.keyCode 및 event.charCode을 정상화. 키보드 키 입력을위한 이벤트를 시청하는 것이 좋습니다.

which 문서.


$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

이 솔루션은 웹 사이트의 모든 양식 (아약스가 삽입 된 양식)에서도 작동하므로 입력 텍스트 입력 만 방지합니다. 문서 준비 기능에 넣고 평생 동안이 문제를 잊어 버리십시오.


ENTER 키에 대한 모든 키 입력을 캡처하고 테스트 해야하는 과도한 노력으로 인해 실제로 버그가 발생하므로 솔루션은 다음 브라우저 동작에 의존합니다.

ENTER를 누르면 제출 버튼 에서 클릭 이벤트 가 트리거됩니다 (IE11, Chrome 38, FF 31에서 테스트).

** (참조 :

http://mattsnider.com/how-forms-submit-when-pressing-enter/

)따라서 내 솔루션은 표준 제출 버튼 (즉

<input type="submit">

) 을 제거하여 ENTER를 누를 때 마술처럼 클릭 할 제출 버튼이 없기 때문에 위의 동작이 실패하도록하는 것입니다. 대신 일반 버튼에서 jQuery 클릭 핸들러를 사용하여 jQuery의

.submit()

메소드 를 통해 양식을 제출합니다 .

<form id="myform" method="post">
  <input name="fav_color" type="text">
  <input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>

<script>
 $('#form-button-submit').click(function(){
    $('#myform').submit();
  });
</script>

데모 :

http://codepen.io/anon/pen/fxeyv?editors=101

** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.


Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :

var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
  e.preventDefault();
  return false;
}

if you just want to disable submit on enter and submit button too use form's onsubmit event

<form onsubmit="return false;">

You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.


You can do this perfectly in pure Javascript, simple and no library required. Here it is my detailed answer for a similar topic: Disabling enter key for form

In short, here is the code:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...


I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!

$j(':input:not(textarea)').keydown(function(event){
    var kc = event.witch || event.keyCode;
    if(kc == 13){
    event.preventDefault();
        $j(this).closest('form').attr('data-oldaction', function(){
            return $(this).attr('action');
        }).attr('action', 'javascript:;');

        alert('some_text_if_you_want');

        $j(this).closest('form').attr('action', function(){
            return $(this).attr('data-oldaction');
        });
        return false;
    }
});

The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.

<script type="text/javascript">
        function stopRKey(evt) {
          var evt = (evt) ? evt : ((event) ? event : null);
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
          if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) )  {return false;}
        }

        document.onkeypress = stopRKey;
</script> 

In firefox, when you at input and press enter, it will submit it's upper form. The solution is in the will submit form add this:

<input type="submit" onclick="return false;" style="display:none" />

3 years later and not a single person has answered this question completely.

The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.

Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:

$("#save-form").on("click", function () {
    $.ajax({
        ...
    });
    return false;
});

The simple way is to change type of button to button - in html and then add event in js...

Change from this:

<form id="myForm">
   <button type="submit">Submit</button>
</form>

To

<form id="myForm">
   <button type="button" id="btnSubmit">Submit</button>
</form>

And in js or jquery add:

("#btnSubmit").click(function () {
    $('#myForm').submit();
});

When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.

<script>
            $(document).ready(function () {
                $(window).keydown(function(event){
                    if(event.keyCode == 13) {
                        e.preventDefault(); // Disable the " Entry " key
                        return false;               
                    }
                });
            });
        </script>

Complete Solution in JavaScript for all browsers

The code above and most of the solutions are perfect. However, I think the most liked one "short answer" which is incomplete.

So here's the entire answer. in JavaScript with native Support for IE 7 as well.

var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});

This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.


How about this:

$(":submit").closest("form").submit(function(){
    $(':submit').attr('disabled', 'disabled');
});

This should disable all forms with submit buttons in your app.

참고URL : https://stackoverflow.com/questions/11235622/jquery-disable-form-submit-on-enter

반응형