UXerUIer
UXerUIer

Reputation: 2338

Canceling a "submit" button execution

I have a submit button in HTML for a form:

<form>
<input type="text" />
<input type="submit" id="execute" />
</form>

I'm trying to apply javascript for a confirm window, and if the user clicks cancel, the submit will not execute. How do I do that?

Upvotes: 1

Views: 73

Answers (6)

melc
melc

Reputation: 11671

HTML

<form action="/" method="post" onsubmit="return check()">
    <input type="text" />
    <input type="submit" id="execute"  />
</form>

JS

function check() {
    if (confirm('submit?')) {
        return true;
    } else {
        return false;
    }
}

http://jsfiddle.net/UJ7Q4/

JS-jQuery

$(document).ready(function () {

    $('input[type="submit"]').on('click', function (e) {
        e.preventDefault();
        if (confirm('submit?')) {
            $('form').submit();
        }
    });

});

HTML

<form action="/" method="post">
    <input type="text" />
    <input type="submit" id="execute" />
</form>

http://jsfiddle.net/rqc5A/

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

How about giving an id to your form

<form id="formname">
  <input type="text" />
  <input type="submit" id="execute" />
</form>

and using

var form = document.getElementById('formname');
form.addEventListener('submit', function(e){
    var question = confirm('Really submit the form ?');
    if (!question){e.preventDefault();}
}, false);

Demo at http://jsfiddle.net/k7XuV/

Upvotes: 0

oemran
oemran

Reputation: 1

<input type="submit" id="execute" 
onclick="if !(confirm('your confirmation message')) return false;"/>

Upvotes: 0

Crackertastic
Crackertastic

Reputation: 4913

Use an if to test the confirm() results:

function checkConfirm() {
    var c = confirm("Your message here...");

    if(c) {
        //User clicked OK, do stuff here, maybe even submit the form
        document.forms['id'].submit();
    } else {
        //User clicked cancel, just quit.
        return false;
    }
}

Then add the function inline to your submit button.

<input type="submit" id="execute" onclick="checkConfirm();" />

Upvotes: 0

Karl-Johan Sj&#246;gren
Karl-Johan Sj&#246;gren

Reputation: 17612

The lazy and easy way.

<form onsubmit="return confirm('Do you want to submit the form?'">

A nicer approach would of course be to put this into a script-file and binding the event onload instead.

Upvotes: 6

Satpal
Satpal

Reputation: 133453

Just return false on click event of button

 <input type="submit" id="execute" onclick="return false;"/>

If you want to use confirm

 <input type="submit" id="execute" onclick="return confirm("Your message");"/>

Upvotes: 1

Related Questions