jQuery - 기본값을 방지한 다음 기본값을 계속합니다.
제출할 때 추가 처리를 해야 양식을 제출할 수 있는 양식을 가지고 있습니다.기본 양식 제출 동작을 방지하고 추가 처리를 수행할 수 있습니다(기본적으로 Google 지도 API를 호출하고 양식에 숨겨진 필드를 몇 개 추가합니다). 그런 다음 제출할 양식이 필요합니다.
기본값을 방지하고 나중에 "기본값을 계속 유지"하는 방법이 있습니까?
사용하다jQuery.one()
요소에 대한 이벤트에 핸들러를 연결합니다.처리기는 이벤트 유형별로 요소당 최대 한 번 실행됩니다.
$('form').one('submit', function(e) {
e.preventDefault();
// do your things ...
// and when you done:
$(this).submit();
});
의 사용.one
또한 이 관습 때문에 무한 루프를 방지합니다.submit
이벤트는 첫번째 제출 후 발송됩니다.
당신이 묶을 때..submit()
양식에 이벤트가 발생하고, 반환하기 전에 하고 싶은 일을 수행합니다(참). 이러한 일들은 실제 제출 전에 발생합니다.
예를 들어,
$('form').submit(function(){
alert('I do something before the actual submission');
return true;
});
jquery.com 의 또 다른 예: http://api.jquery.com/submit/ #entry-
저는 그냥 이렇게 하겠습니다.
$('#submiteButtonID').click(function(e){
e.preventDefault();
//do your stuff.
$('#formId').submit();
});
불러preventDefault
처음부터 사용할 때까지submit()
만약 당신이 양식을 제출하기만 하면 나중에 기능합니다.
$('#myform').on('submit',function(event){
// block form submit event
event.preventDefault();
// Do some stuff here
...
// Continue the form submit
event.currentTarget.submit();
});
이 방법으로 당신은 당신의 JS에 끝없는 루프를 할 것입니다. 더 나은 방법을 하기 위해 당신은 다음을 사용할 수 있습니다.
var on_submit_function = function(evt){
evt.preventDefault(); //The form wouln't be submitted Yet.
(...yourcode...)
$(this).off('submit', on_submit_function); //It will remove this handle and will submit the form again if it's all ok.
$(this).submit();
}
$('form').on('submit', on_submit_function); //Registering on submit.
도움이 됐으면 좋겠네요!감사합니다!
IMHO는 가장 일반적이고 강력한 솔루션입니다(사용자가 작업을 수행할 때 '사용자가 버튼을 클릭하는 경우'와 같이).
- 핸들러를 처음 호출할 때 WHO가 트리거한 것을 확인합니다.
- 사용자가 트리거한 경우 - 작업을 수행한 다음 다시 트리거(원하는 경우) - 프로그래밍 방식으로 실행합니다.
- 그렇지 않으면 - 아무것도 하지 않습니다(= "continue 기본값").
예를 들어, 버튼을 속성으로 장식하는 것만으로 "Are you sure?" 팝업을 버튼에 추가할 수 있는 우아한 솔루션에 주목하십시오.사용자가 선택하지 않으면 조건부로 기본 동작을 계속합니다.
1. 원하는 모든 버튼에 "Are you sure" 팝업이 표시되고 경고 텍스트가 표시됩니다.
<button class="btn btn-success-outline float-right" type="submit" ays_text="You will lose any unsaved changes... Do you want to continue?" >Do something dangerous</button>
2. 핸들러를 모든 이러한 버튼에 부착합니다.
$('button[ays_text]').click(function (e, from) {
if (from == null) { // user clicked it!
var btn = $(this);
e.preventDefault();
if (confirm() == true) {
btn.trigger('click', ['your-app-name-here-or-anything-that-is-not-null']);
}
}
// otherwise - do nothing, ie continue default
});
바로 그겁니다.
와 함께jQuery
그리고 위의 @Joepreludian의 답변을 약간 변형한 것입니다.
유의해야 할 중요 사항:
.one(...)
대신에.on(...) or .submit(...)
named
대신에 기능함anonymous function
우리가 그것을 참조할 것이기 때문에.callback
.
$('form#my-form').one('submit', function myFormSubmitCallback(evt) {
evt.stopPropagation();
evt.preventDefault();
var $this = $(this);
if (allIsWell) {
$this.submit(); // submit the form and it will not re-enter the callback because we have worked with .one(...)
} else {
$this.one('submit', myFormSubmitCallback); // lets get into the callback 'one' more time...
}
});
의 값을 변경할 수 있습니다.allIsWell
아래 토막글의 변수:true
아니면false
기능 테스트 방법:
$('form#my-form').one('submit', function myFormSubmitCallback(evt){
evt.stopPropagation();
evt.preventDefault();
var $this = $(this);
var allIsWell = $('#allIsWell').get(0).checked;
if(allIsWell) {
$this.submit();
} else {
$this.one('submit', myFormSubmitCallback);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/" id="my-form">
<input name="./fname" value="John" />
<input name="./lname" value="Smith" />
<input type="submit" value="Lets Do This!" />
<br>
<label>
<input type="checkbox" value="true" id="allIsWell" />
All Is Well
</label>
</form>
행운을...
"제출 루프 없이 유효성 검사 주입":
HTML5 검증 전에 reCaptcha 등을 확인하고 싶어서 그런 작업을 했습니다(검증 기능이 true 또는 false를 반환함).
$(document).ready(function(){
var application_form = $('form#application-form');
application_form.on('submit',function(e){
if(application_form_extra_validation()===true){
return true;
}
e.preventDefault();
});
});
순수 자바스크립트 방식으로 디폴트 방지 후 폼 제출이 가능합니다.
왜냐하면HTMLFormElement.submit()
절대로 전화하지 않습니다onSubmit()
는 마치 에 대한 그 그래서 우리는 여기에 제출 처리자에 대한 관습이 없는 것처럼 양식을 제출하기 위해 그 사양 특이점에 의존하고 있습니다.
var submitHandler = (event) => {
event.preventDefault()
console.log('You should only see this once')
document.getElementById('formId').submit()
}
동기화 요청에 대해서는 이 fidle을 참조하십시오.
비동기 요청이 완료되기를 기다리는 것도 마찬가지로 쉽습니다.
var submitHandler = (event) => {
event.preventDefault()
console.log('before')
setTimeout(function() {
console.log('done')
document.getElementById('formId').submit()
}, 1400);
console.log('after')
}
비동기적인 요청의 예를 위해 제 fiddle을 확인할 수 있습니다.
그리고 약속에 동의하지 않는다면:
var submitHandler = (event) => {
event.preventDefault()
console.log('Before')
new Promise((res, rej) => {
setTimeout(function() {
console.log('done')
res()
}, 1400);
}).then(() => {
document.getElementById('bob').submit()
})
console.log('After')
}
그리고 여기 그 요청이 있습니다.
사용가능e.preventDefault()
현재 작동을 중지합니다.
자네가 할 수 있는 한$("#form").submit();
$('#form').submit(function (e)
{
return !!e.submit;
});
if(blabla...)
{...
}
else
{
$('#form').submit(
{
submit: true
});
}
언급URL : https://stackoverflow.com/questions/14375144/jquery-prevent-default-then-continue-default
'programing' 카테고리의 다른 글
C - R 프로그래머의 경우 - 기본을 초과한 경우 권장 리소스/접근 방법 (0) | 2023.10.22 |
---|---|
AngularJS - ng-show in ng-repeat 사용 (0) | 2023.10.22 |
Perf 캐시 이벤트란 무엇을 의미합니까? (0) | 2023.10.22 |
일부 매크로의 출처를 찾는 방법 (0) | 2023.10.22 |
spring boot이 logback-spring.xml을 무시합니다. (0) | 2023.10.22 |