JavaScript에서 양식 제출 캡처
javascript를 사용하여 양식을 제출하는 방법에 대한 많은 정보가있는 것 같지만 양식이 제출되었을 때 캡처하고 javascript에서 가로 챌 솔루션을 찾고 있습니다.
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
<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()
이벤트를 첨부 한 요소가로드되기 전에는 이벤트를 첨부 할 수 없습니다.
이것은 작동합니다-
일반 JS
eventListener 사용 권장
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
alert('hi');
});
});
하지만 하나 이상의 리스너가 필요하지 않은 경우 onload 및 onsubmit을 사용할 수 있습니다.
// Should only be triggered on first page load
alert('ho');
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
/* do what you want with the form */
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
}
jQuery
// Should only be triggered on first page load
alert('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
alert('hi');
});
});
<form onSubmit="return captureForm()">
그렇게해야합니다. captureForm()
메서드가를 반환 하는지 확인하십시오 false
.
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);
@Kristian Antonsen의 답변을 사용하거나 다음을 사용할 수 있습니다.
$('button').click(function() {
preventDefault();
captureForm();
});
참고URL : https://stackoverflow.com/questions/5384712/capture-a-form-submit-in-javascript
'developer tip' 카테고리의 다른 글
Javascript / jQuery에서 문자열의 픽셀 길이를 결정합니까? (0) | 2020.11.11 |
---|---|
Linux 용 예쁘고 기능이 풍부한 Git GUI (0) | 2020.11.11 |
Facebook 페이지의 피드를 내 웹 사이트에 삽입하는 방법 (0) | 2020.11.11 |
DateInterval 형식에서 'P'는 무엇을 의미합니까? (0) | 2020.11.11 |
중첩 함수가 외부 함수의 변수에 액세스 할 수 있지만 수정할 수없는 이유 (0) | 2020.11.11 |