简体   繁体   中英

JavaScript Prevent Form Submit

I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.

I have this code:

  $(document).ready(function() {
    $("#submit").click(function (e) {
        e.preventDefault();
        var link = $(this).attr("href"); // "get" the intended link in a var
        var result = confirm("Are you sure you want to log this fault?");
        if (result) {
            document.location.href = link;  // if result, "set" the document location      
        }
    });
});

The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.

My HTML code is:

<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">

<!-- other elements -->
....
....
....

<button type="submit" id="submit" class="btn btn-default">
    <span class="glyphicon glyphicon-floppy-save"></span>
</button>

</form>

$(function() {
    //this would do the same as button click as both submit the form
    $(document).on("submit", "#myform", function (e) {
        var result = confirm("Are you sure you want to log this fault?");
        //if cancel is cliked
        if (!result) {
             return false;      
        }
        //if ok is cliked, form will be submitted
    });
});

the following like won't work since this reffers to the submit button which does not have an href attribute.

var link = $(this).attr("href"); // is invalid.

try

 $(document).ready(function() {
    $("#submit").click(function (e) {
        e.preventDefault();
        var result = confirm("Are you sure you want to log this fault?");
        if (result) {
        $('#formId').submit(); // where formId is the id of your form
          document.location.href = "url to which you want to redirect";      
        }
        else
        return false;
       });
});

side note: from wherever you got this piece of code, they must be using a hyperlink <a> styled like a button, with a valid href attribute :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM