Confirm before a form submit

前端 未结 7 1331
孤城傲影
孤城傲影 2020-12-05 07:38

I have searched for an answer but couldn\'t find one!

I have a simple form,

相关标签:
7条回答
  • 2020-12-05 08:18

    HTML:

    <form action="adminprocess.php" method="POST" id="myCoolForm">
        <input type="submit" name="completeYes" value="Complete Transaction" />
    </form>
    

    JavaScript:

    var el = document.getElementById('myCoolForm');
    
    el.addEventListener('submit', function(){
        return confirm('Are you sure you want to submit this form?');
    }, false);
    

    Edit: you can always use inline JS code like this:

    <form action="adminprocess.php" method="POST" onsubmit="return confirm('Are you sure you want to submit this form?');">
        <input type="submit" name="completeYes" value="Complete Transaction" />
    </form>
    
    0 讨论(0)
  • 2020-12-05 08:21

    if you have more then one submit buttons that do different actions you can do it this way.

    <input TYPE=SUBMIT NAME="submitDelete"  VALUE="Delete Script" onclick='return window.confirm("Are you sure you want to delete this?");'>
    
    0 讨论(0)
  • 2020-12-05 08:22

    The correct event is onSubmit() and it should be attached to the form. Although I think it's possible to use onClick, but onSubmit is the correct one.

    0 讨论(0)
  • 2020-12-05 08:23
    <input type="submit" onclick="return confirm('Are you sure you want to do that?');">
    
    0 讨论(0)
  • 2020-12-05 08:30

    In my case, I didn't have a form ID and couldn't add inline in the form tag. I ended up with the following jQuery code

        var form = $("form").first();
        form.on('submit', function() {
            return confirm('Are you sure you want to submit this form?');
        });
    
    0 讨论(0)
  • 2020-12-05 08:34

    var submit = document.querySelector("input[type=submit]");
      
    /* set onclick on submit input */   
    submit.setAttribute("onclick", "return test()");
    
    //submit.addEventListener("click", test);
    
    function test() {
    
      if (confirm('Are you sure you want to submit this form?')) {         
        return true;         
      } else {
        return false;
      }
    
    }
    <form action="admin.php" method="POST">
      <input type="submit" value="Submit" />
    </form>

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