54

I'm trying to stop my form from submitting if a validation fails. I tried following this previous post but I doesn't work for me. What am I missing?

<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>
Community
  • 1
  • 1
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
  • which function in the above code is stopping the form from submitting? What is showMsg function doing? Why are you using sender.preventDefault(); Is sender argument an event? preventDefault() is used to stop the normal behaviour of an element upon some event like click etc. – DG3 Apr 10 '12 at 16:25
  • sender is referring to e : event – Antarr Byrd Apr 10 '12 at 16:34

5 Answers5

105

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

Move the e.preventDefault(); as first line in the click handler.

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

See below code,

I want it to be allowed 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();
    }
}
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
15

use this too :

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

Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Arjun Raj
  • 984
  • 2
  • 12
  • 32
  • 10
    in case you use jQuery you can safely use `e.preventDefault()`. jQuery will take care for the x-browser compatibility. – staabm Mar 11 '14 at 10:00
  • From the [jQuery on](http://api.jquery.com/on/) API: "Returning false from an event handler will automatically call `event.stopPropagation()` and `event.preventDefault()`." It goes on to say: "A `false` value can also be passed for the handler as a shorthand for `function(){ return false; }`" – Paul Aug 21 '15 at 19:01
3

Try the code below. e.preventDefault() was added. This removes the default event action for the form.

 $(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
       });
     }


    });
 });
Downpour046
  • 1,661
  • 9
  • 14
  • I'm not actually validating a field. This ajax portion of the code calls a method that checks if a job for the client is already in progress. I don't want to allow multiple jobs for the same client to be enqueue. – Antarr Byrd Apr 10 '12 at 16:39
3

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();"/>
    }
Sandeep
  • 615
  • 6
  • 13
0

This is a JQuery code for Preventing Submit

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });
keivan kashani
  • 1,263
  • 14
  • 15