programing

양식 제출 전 jQuery 기능

sourcejob 2023. 10. 16. 21:48
반응형

양식 제출 전 jQuery 기능

폼 제출 버튼을 클릭하면 Jquery를 사용하여 기능을 실행하려고 하는데 폼이 실제로 제출되기 전에 기능을 실행해야 합니다.

몇 개 복사하려고 합니다.div제출 시 숨겨진 텍스트 필드에 속성을 태그한 다음 양식을 제출합니다.

저는 이것을 사용하여 작동시킬 수 있었습니다.mouseover(제출 버튼이 위로 이동할 때) 기능하지만, 이 기능은 터치를 사용하는 모바일 장치에서는 작동하지 않습니다.

$("#create-card-process.design #submit").on("mouseover", function () {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

나는 그것을 가지고 놀았습니다.submitfunction, 그러나 function은 이전이 아닌 폼이 제출될 때 function이 실행되므로 필드 내에 값이 저장되지 않습니다.

대단히 고맙습니다.

on submit 기능을 사용하시면 됩니다.

거짓으로 회신하면 양식이 제출되지 않습니다.여기서 읽어보세요.

$('#myform').submit(function() {
  // your code here
});
$('#myform').submit(function() {
  // your code here
})

위 내용은 Firefox에서 작동하지 않습니다.먼저 코드를 실행하지 않고 양식만 제출하면 됩니다.또한 다른 곳에서도 비슷한 문제들이 언급되고 있습니다.이 문제와 같은 것해결 방법은 다음과 같습니다.

$('#myform').submit(function(event) {

 event.preventDefault(); //this will prevent the default submit

  // your code here (But not asynchronous code such as Ajax because it does not wait for a response and move to the next line.)
  
 $(this).unbind('submit').submit(); // continue the submit unbind preventDefault
})

와카스 부하리의 답변을 바탕으로 응답 범위에 마지막 줄을 넣어 비동기화 할 수 있습니다.

$('#myform').submit(function(event) {

  event.preventDefault(); //this will prevent the default submit
  var _this = $(this); //store form so it can be accessed later

  $.ajax('GET', 'url').then(function(resp) {

    // your code here 

   _this.unbind('submit').submit(); // continue the submit unbind preventDefault
  })  
}

저는 현대적인 2021년 10월 답변을 드리고 싶었습니다.현재의,$('form').on('submit', function(event) {...})는 몇 가지 특정한 경우에 실제 제출 전에 실행되지 않습니다.숨겨진 입력에 필요파이어폭스HTML5 사용.

크롬, 파이어폭스, 브레이브에서 다음 솔루션을 테스트했습니다.설정만 하면 됩니다.onClick()이벤트 처리기로 제출 버튼을 선택합니다.다음으로 제출을 취소할 수 있습니다.event.preventDefault();당신이 제출을 원하지 않는다면 말입니다.또한 텍스트 또는 확인란 입력을 선택하고 Enter 키를 누르면 여전히 호출됩니다.onClick이벤트는 No-onClick이 발생했음에도 불구하고 브라우저는 이를 클릭하는 바로가기로 이해하기 때문입니다.<input type="submit">.

var allowSubmit = false;
document.querySelector('#submit').addEventListener('click', function(event) {
    if(allowSubmit) {
        console.log("Submit allowed.");
        return true;
    }
    
    console.log("Submit prevented.");
    
    event.preventDefault();
    return false;
});
<input type="submit" id="submit" value="Submit Button">

요즘은 "제출 전" jquery form 이벤트를 참조하여 다음과 같은 작업을 할 수 있습니다.중복 요청을 피하기 위해 제출 버튼을 비활성화 및 활성화하고 있습니다. ajax를 통해 제출하고 json 배열인 메시지를 반환하고 pNotify:

jQuery('body').on('beforeSubmit', "#formID", function() {
    $('.submitter').prop('disabled', true);
    var form = $('#formID');
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        data   : form.serialize(),
        success: function (response)
        {
            response = jQuery.parseJSON(response);
            new PNotify({
                text: response.message,
                type: response.status,
                styling: 'bootstrap3',
                delay: 2000,
            });
            $('.submitter').prop('disabled', false);
        },
        error  : function ()
        {
            console.log('internal server error');
        }
    });
});

아악.... submit 함수를 처음 시도했을 때 코드를 놓쳤어요...

작동 내용:

$('#create-card-process.design').submit(function() {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

댓글 달아주셔서 감사합니다.

버튼 대신 디바 스팬을 사용한 후 클릭하면 끝에 양식을 제출하는 함수를 호출할 수 있습니다.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>

제출 기능을 사용할 때 매번 이런 실수를 했다고 해서요.

필요한 전체 코드는 다음과 같습니다.

HTML 양식 태그에 ID "your id"를 추가합니다.

<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>

jQuery 코드:

$('#yourid').submit(function() {
  // do something
});

언급URL : https://stackoverflow.com/questions/21938788/jquery-function-before-form-submission

반응형