JavaScript에서 양식 제출을 가로 채 정상적인 제출 방지


84

자바 스크립트를 사용하여 양식을 제출하는 방법에 대한 많은 정보가있는 것 같지만 양식이 제출 된시기를 캡처하고 자바 스크립트에서 가로 챌 솔루션을 찾고 있습니다.

HTML

<form>
 <input type="text" name="in" value="some data" />
 <button type="submit">Go</button>
</form>

사용자가 제출 (submit) 버튼을 누를 때, 나는 할 수 없습니다 양식을 제출하려면, 대신에 나는 자바 스크립트 함수를 호출 할 수 싶습니다.

function captureForm() {
 // do some stuff with the values in the form
 // stop form from being submitted
}

빠른 해킹은 버튼에 onclick 기능을 추가하는 것입니다.하지만이 솔루션이 마음에 들지 않습니다. 양식을 제출하는 방법은 여러 가지가 있습니다. 예를 들어 입력 중에 Return 키를 누르면 설명되지 않습니다.

Ty


답변:


96
<form id="my-form">
    <input type="text" name="in" value="some data" />
    <button type="submit">Go</button>
</form>

JS에서 :

function processForm(e) {
    if (e.preventDefault) e.preventDefault();

    /* do what you want with the form */

    // You must return false to prevent the default form behavior
    return false;
}

var form = document.getElementById('my-form');
if (form.attachEvent) {
    form.attachEvent("submit", processForm);
} else {
    form.addEventListener("submit", processForm);
}

편집 : 내 생각에이 접근 방식은 onSubmit마크 업과 기능의 분리를 유지하기 때문에 양식에 속성을 설정하는 것보다 낫 습니다. 하지만 그건 내 2 센트에 불과합니다.

Edit2 : 포함하도록 내 예제 업데이트preventDefault()


이 중 지금까지 내가 사용하여 볼 수있는 크롬하지 작업을 수행 jsbin.com/ejoyas
Eiyrioü 폰 Kauyf을

2
dom에서 양식을 사용할 수있게되면 첨부 이벤트 코드를 실행해야합니다. 사용 예를 들어 window.onload=function() { ... }그것을 포장
mplungjan

processform()함수는 언제 호출됩니까?

IE를 사용하지 않기 때문에 확실하지 않지만 attachEvent 매개 변수는 "onsubmit"이어야한다고 생각합니다.
Gerard ONeill 2015-06-10

이것은 크롬 46에서 작동하지 않습니다. 이벤트 첨부시 오류, 페이지를 먼저로드해야합니다
tsukimi

28

이벤트를 첨부 한 요소가로드되기 전에는 이벤트를 첨부 할 수 없습니다.

이것은 작동합니다-

일반 JS

데모

eventListener 사용 권장

// Should only be triggered on first page load
console.log('ho');

window.addEventListener("load", function() {
  document.getElementById('my-form').addEventListener("submit", function(e) {
    e.preventDefault(); // before the code
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log('hi');
  })
});
<form id="my-form">
  <input type="text" name="in" value="some data" />
  <button type="submit">Go</button>
</form>

하지만 하나 이상의 리스너가 필요하지 않은 경우 onload 및 onsubmit을 사용할 수 있습니다.

// Should only be triggered on first page load
console.log('ho');

window.onload = function() {
  document.getElementById('my-form').onsubmit = function() {
    /* do what you want with the form */

    // Should be triggered on form submit
    console.log('hi');
    // You must return false to prevent the default form behavior
    return false;
  }
}
    <form id="my-form">
      <input type="text" name="in" value="some data" />
      <button type="submit">Go</button>
    </form>

jQuery

// Should only be triggered on first page load
console.log('ho');

$(function() {
  $('#my-form').on("submit", function(e) {
    e.preventDefault(); // cancel the actual submit

    /* do what you want with the form */

    // Should be triggered on form submit

    console.log('hi');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
  <input type="text" name="in" value="some data" />
  <button type="submit">Go</button>
</form>


내 생각에는 $ ( '# my-form) .on ('submit ', function () {alert ('hi ');});
Michiel 2013

1
@Michiel 제공하는 것은 jQuery와 함께 사용하는 것이지만 제공된이 솔루션은 jQuery에 종속되지 않는 순수한 JS 솔루션입니다. 사용하는 여기 것 유사한 솔루션<form onsubmit="alert('hi'); return false;">
크리스 Marisic을

2
@ChrisMarisic는 - 내가 대답을 업데이트 한 : 몇 살 어쨌든 jQuery를 포함하는
mplungjan

17

<form onSubmit="return captureForm()"> 그렇게해야합니다. captureForm()메서드가를 반환 하는지 확인하십시오 false.


후속 조치 : 브라우저의 필수 속성 처리에 영향을주지 않고 JavaScript로 양식 제출을 캡처하는 방법이 있습니까?
Elisabeth

@Elisabeth 어떤 속성을 처리합니까? 양식이 실제로 제출되는 것을 막지 않으려면 대신 captureForm()반환하면 true됩니다 false.
kba 2011

브라우저의 "필수"속성 처리. 양식이 제출되는 것을 막고 싶습니다. 그러나 true 대신 false를 반환하거나 preventDefault ()를 사용하여 브라우저가 입력 요소에서 "required"속성을 처리하는 방법을 변경합니다. 직접 시도해보세요. 입력 요소에 <code> required </ code>를 추가하고 제출을 캡처 한 다음 기본 동작을 잃어 버리는 지 확인하세요.
Elisabeth

기본 동작을 잃지 않는 것 같습니다. Chrome에서 잘 작동합니다. 제가 도움을 드리려면 잘못된 예를 제시해야합니다.
kba 2011

1
좋습니다. 양식은 다음과 같습니다. <form method = "get"action = ""> <label for = "color"> 좋아하는 색상은 무엇입니까? </ label> <input type = "text"name = "color"placeholder = "파란색"필수> <input id = "submit"type = "submit"value = "Submit"> </ form> 코드는 다음과 같습니다. function processForm (e) {var form = document.querySelector ( "form"); for (var i = 0; i <form.childNodes.length; i ++) {var node = form.childNodes [i]; / * 노드로 작업 수행 /} / return false; * /} 오페라에서 테스트. 마지막 줄의 주석 처리를 제거하면 필수가 실패합니다. (죄송합니다 코드는 주석에서 잘 작동하지 않습니다)
Elisabeth

6

onload가 도움이되지 않는 경우에 대해 실습에서 사용한 모든 요청을 처리하는 또 다른 옵션은 javascript submit, html submit, ajax 요청을 처리하는 것입니다. 이러한 코드는 양식을 렌더링하고 제출하기 전에 리스너를 만들려면 본문 요소의 맨 위에 추가해야합니다.

예를 들어 페이지로드 전에 발생하더라도 제출시 페이지의 모든 양식에 숨겨진 필드를 설정합니다.

//Handles jquery, dojo, etc. ajax requests
(function (send) {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    XMLHttpRequest.prototype.send = function (data) {
        if (isNotEmptyString(token) && isNotEmptyString(header)) {
            this.setRequestHeader(header, token);
        }
        send.call(this, data);
    };
})(XMLHttpRequest.prototype.send);


//Handles javascript submit
(function (submit) {
    HTMLFormElement.prototype.submit = function (data) {
        var token = $("meta[name='_csrf']").attr("content");
        var paramName = $("meta[name='_csrf_parameterName']").attr("content");
        $('<input>').attr({
            type: 'hidden',
            name: paramName,
            value: token
        }).appendTo(this);

        submit.call(this, data);
    };
})(HTMLFormElement.prototype.submit);


//Handles html submit
document.body.addEventListener('submit', function (event) {
    var token = $("meta[name='_csrf']").attr("content");
    var paramName = $("meta[name='_csrf_parameterName']").attr("content");
    $('<input>').attr({
        type: 'hidden',
        name: paramName,
        value: token
    }).appendTo(event.target);
}, false);

2

@Kristian Antonsen의 답변을 사용하거나 다음을 사용할 수 있습니다.

$('button').click(function() {
    preventDefault();
    captureForm();
});

3
2.5 년 (또는 그 이상) function(e)e.preventDefault()
후에이

또한 입력 [type = "submit"]이 사용되는 경우 양식의 "제출"이벤트에서 캡처 할 수 있으며 이는 단추의 컨텍스트 대 양식 컨텍스트에 놓이게합니다. 콜백은 항상 이벤트의 컨텍스트를 가지므로 반드시 'e'를 인수로 전달할 필요는 없으며 단순히 '이벤트'를 참조하면됩니다.
augurone

1
제출은 키 누르기로 트리거 될 수 있으므로 권장되지 않습니다.
jhpratt
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.