My html page has a submit button created as follows:
<input type="submit" name="submit" value="Remove" class="remove" onclick="return window.confirm( Are you sure you want to remove this?)">
When a user clicks this button I need to detect if they select OK or Cancel.
I’m trying to do this using the following which is running in my js script.
$("body").on('click', '.remove', function(e) {
e.preventDefault()
var _confirm_function = window.confirm;
window.confirm = function() {
var confirmed = _confirm_function.apply( window, arguments );
console.log ( confirmed )
if ( confirmed !== true ) {
console.log ( "user pressed cancel: Some cleanup");
return false
} else {
console.log ( "user pressed ok: Do tasks");
}
}
})
When the page is loaded this doesn’t seem to fire on the first click of the button. The second click of the button it works, but even if it returns false it carries on through the script and doesn’t return false. Subsequent clicks of the button seem to be firing multiple times.
I need to have this run as soon as the button is clicked, and if Cancel is selected it should stop and not do anything further.
Is there any way to do this ?
Thanks
2
Answers
Your code seems very confused, window.confirm() itself already returns a boolean indicating which button was pressed. Why not use that? Something like this:
HTML
JAVASCTIPT
It doesn’t quite make sense that this function should be placed in a submit button. A submit button is usually part of a form, and, as your code is now, this form will be submitted regardless of the answer of the user. You shouldn’t be using a submit button if there is no form. See also: HTML submit button onclick code.
Assuming your submit button (whose name needs to NOT be submit), is in a form
If NOT in a form, make it a button: