Reputation: 2338
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
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;
}
}
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>
Upvotes: 1
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
Reputation: 1
<input type="submit" id="execute"
onclick="if !(confirm('your confirmation message')) return false;"/>
Upvotes: 0
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
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
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