Development Tip

양식 제출 중지, Jquery 사용

yourdevel 2021. 1. 10. 19:40
반응형

양식 제출 중지, Jquery 사용


유효성 검사에 실패하면 양식 제출을 중지하려고합니다. 이전 게시물을 따라 시도했지만 나를 위해 작동하지 않습니다. 내가 무엇을 놓치고 있습니까?

<input id="saveButton" type="submit" value="Save" />
<input id="cancelButton" type="button" value="Cancel" />
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        $("form").submit(function (e) {
            $.ajax({
                url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
                data: { id: '@Model.ClientId' },
                success: function (data) {
                    showMsg(data, e);
                },
                cache: false
            });
        });
    });
    $("#cancelButton").click(function () {
        window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
    });
    $("[type=text]").focus(function () {
        $(this).select();
    });
    function showMsg(hasCurrentJob, sender) {
        if (hasCurrentJob == "True") {
            alert("The current clients has a job in progress. No changes can be saved until current job completes");
            if (sender != null) {
                sender.preventDefault();
            }
            return false;
        }
    }

</script>

다시 말하지만 AJAX는 비동기입니다. 따라서 showMsg 함수는 서버의 성공 응답 후에 만 ​​호출됩니다. 양식 제출 이벤트는 AJAX 성공까지 기다리지 않습니다.

e.preventDefault();클릭 처리기에서 첫 번째 줄로 이동 합니다.

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

아래 코드를 참조하십시오.

HasJobInProgress == False를 허용하고 싶습니다.

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

이것도 사용하십시오 :

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault () 는 IE (일부 버전)에서 지원되지 않습니다. IE에서는 e.returnValue = false입니다.


아래 코드를 시도하십시오. e.preventDefault ()가 추가되었습니다 . 그러면 양식에 대한 기본 이벤트 조치가 제거됩니다.

 $(document).ready(function () {
    $("form").submit(function (e) {
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
        });
        e.preventDefault();
    });
});

Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?

Here is an example of some added validation

 $(document).ready(function () {
    $("form").submit(function (e) {
      /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
    if(!$('#inputID').val()){ 
       e.preventDefault(); // This will prevent the form submission
     } else{
        // In the event all validations pass. THEN process AJAX request.
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
       });
     }


    });
 });

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

This is a JQuery code for Preventing Submit

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });

ReferenceURL : https://stackoverflow.com/questions/10092580/stop-form-from-submitting-using-jquery

반응형