JavaScript Prevent Form Submit

前端 未结 2 1039
遥遥无期
遥遥无期 2021-01-28 20:14

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() {
             


        
相关标签:
2条回答
  • 2021-01-28 20:37
    <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
        });
    });
    
    0 讨论(0)
  • 2021-01-28 20:38

    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 :)

    0 讨论(0)
提交回复
热议问题