How to prevent JQuery from executing after hitting Cancel on popup? - javascript

I have a form that needs to get submitted. After clicking on submit I have a javascript alert/confirm that asks: Are you sure you want to submit the order?
If the user clicks "OK", I want to execute a JQuery method. But if they click "Cancel", I don't want to execute anything. Is there a way to do this?
Here's the JQuery I want to submit if they click "Ok":
<script>
$(document).ready(function() {
$('#saving').click(function() {
// do something
});
});
</script>
my button:
Save
The javascript popup:
function askUserIfTheyAreSure() {
var check = confirm("Are you sure you want to submit the order?");
if(check == true) {
document.forms["myform"].submit();
}
}

I suggest this way:
<script>
$(document).ready(function() {
$('#saving').click(function() {
if(confirm("Are you sure you want to submit the order?")){
document.forms["myform"].submit();
}else{
return false;
}
});
});
</script>

Do you mean, like this?
<script type='text/javascript'>
function askUserIfTheyAreSure(){
var check = confirm('Are you sure you want to submit the order?');
if(check == 1) {
// run you jQuery Function Here
}
else{
// do something else
return false;
}
}
$(document).ready(function(){
$('#saving').click(askUserIfTheyAreSure);
</script>
Really, I would use external JavaScript, so it's cached.

Just copy whatever you have inside "click" code into the "check==true" block.
It won't be executed if user clicks cancel.
function askUserIfTheyAreSure() {
var check = confirm("Are you sure you want to submit the order?");
if(check == true) {
// do something begin
// do something end
document.forms["myform"].submit();
}
}

Related

Javascript confirm box, click cancel not working, page still load

I have a project use confirm box javascript, if user click cancel and then do nothing but page still load, i search all about confirm box and i can't find what i looking for, please help me with this, here some code
javascript
function OnClickNextPage(){
var result = confirm("Are you sure ?");
if (!result) {
return false;
}
}
html
Test
Thank you
Instead of returning false you have to prevent the default beahaviour of the event with preventDefault() function. Here is the code
Test
function OnClickNextPage(event){
var result = confirm("Are you sure ?");
if (!result) {
event.preventDefault();
}
}
You have to "terminate" the click event to the a tag, to do this, you have pass the event object to OnClickNextPage function, then call .preventDefault() on the event. return false; action does not affect to onclick event.
HTML
Test
Javascript
function OnClickNextPage(event) {
var result = confirm("Are you sure ?");
if (!result) {
event.preventDefault(); // prevent event when user cancel
}
// go to page in a tag's href when user choose 'OK'
}
try
function OnClickNextPage(e){
e.preventDefault();
var result = confirm("Are you sure ?");
if (!result) {
return false;
}
}
Edit --
Sorry My bad, problem is you are calling page load event in href which eventually fire on priority of DOM
Test
Try like this
Test
function OnClickNextPage(e){
e.preventDefault();
var result = confirm("Are you sure ?");
if (!result) {
return false;
} else {
window.location.href = [[Your URL Here]]
}
}
JS
function OnClickNextPage(e){
console.log('after prevent')
var result = confirm("Are you sure ?");
if (!result) {
e.preventDefault();
return false;
}
}
HTML
Test

Javascript confirm Stop page refresh after cancel

I have made a JavaScript function which is attached to the cancel button on of a form. The issue I am finding is that when the cancel button is pressed the page/form reloads losing the data in the text fields.
function cancelConfirm(){
var confirmCancel = confirm("Are you sure you wish to cancel?");
if(confirmCancel==true)
{
alert("byebye");
}
else
{
return false;
}
};
I was just wondering how can you prevent the page from reloading after the cancel button on the confirm has been clicked? Thanks for any help you can give
you can just use a simple way
Delete
function cancelConfirm() {
var confirmCancel = confirm("Are you sure you wish to cancel?");
if (confirmCancel == true) {
alert("byebye");
return false;// to stop postback on ok cick of confirmation popup
}
else {
return false;
}
}
What you can do is to add an onClick event and pass the event object down to it.
{onClick(e) => {
e.preventDefault();
//do something here
}}
A simple e.preventDefault() is what you need.

Jquery simple if statement confusion

I got a confirmation alert to confirm a user action.
on click "ok", it should do the following code:
function disableSubmitButton() {
jQuery("#submitButton").attr("disabled", "true");
jQuery("#rent_space").submit();
}
on "cancel", the following.
if (!confirm('Are you sure you want to proceed ?')) {
return false;
}
However, the way my code is currently formated, the first block of code is executed regardless of which button is pressed.
I think this is pretty much just moving the code around, but I'm unsure how to correctly do it as my precedent attempts all failed. Any help appreciated. Thanks !
Full code:
<script>
jQuery(document).ready(onDocumentReady);
function onDocumentReady() {
jQuery("#submitButton").click(disableSubmitButton);
jQuery('#submitButton').click(function() {
if (!confirm('Are you sure you want to proceed ?')) {
return false;
}
});
}
function disableSubmitButton() {
jQuery("#submitButton").attr("disabled", "true");
jQuery("#rent_space").submit();
}
</script>
You can try:
//jQuery("#submitButton").click(disableSubmitButton);
jQuery('#submitButton').click(function() {
if (!confirm('Are you sure you want to proceed ?')) {
return false;
}
else
{
disableSubmitButton();
}
});
Do you really need to disable the submit button? Returning false on the other click should be enough.
<script>
jQuery(document).ready(onDocumentReady);
function onDocumentReady() {
jQuery('#submitButton').click(function() {
if (!confirm('Are you sure you want to proceed ?')) {
return false;
}
});
}
</script>
However I would instead bind to the submit event:
<script>
jQuery(document).ready(onDocumentReady);
function onDocumentReady() {
jQuery('#rent_space').submit(function() {
if (!confirm('Are you sure you want to proceed ?')) {
return false;
}
});
}
</script>
You only need one event listener. The condition can be handled in the listener body.
jQuery("#submitButton").click(function(e) {
e.preventDefault();
if(confirm("...")) {
jQuery("#submitButton").attr("disabled", "true");
jQuery("#rent_space").submit();
}
});
NB. you should use e.preventDefault() instead of return false to prevent the default behaviour of an event.
Hari's answer is correct. I prefer the (slightly) more idiomatic:
jQuery("#submitButton").click(function() {
if (confirm("Are you sure you want to proceed?")) {
disableSubmitButton();
} else {
return false;
}
});
EDIT EDIT I got it to work thanks to your suggestions. Thank you. :)
Heres the code that worked.
<script>
jQuery(document).ready(onDocumentReady);
function onDocumentReady() {
jQuery('#submitButton').click(function() {
if (!confirm('Are you sure you want to proceed ?')) {
return false;
}
else{
jQuery("#submitButton").click(disableSubmitButton);
}
});
}
function disableSubmitButton() {
jQuery("#submitButton").attr("disabled", "true");
jQuery("#rent_space").submit();
}
</script>

Javascript:Block form submit on Enter Key press

I have a web page where i have 2 forms when i click the enter key, I am calling a javascript function to force the page to load another page.My code is
function SearchUser()
{
var text = document.getElementById("searchItem").value;
text = text == "" ? -1 : text;
var by = document.getElementById("listBy").value;
var on="";
if(by==1)
{
on="USERNAME";
}
else if(by==2)
{
on="FIRSTNAME";
}
else if(by==3)
{
on="EMAIL_ID";
}
gotoUrl="userlist.php?searchItem="+text+"&onSearch="+on;
alert(gotoUrl);
window.navigate=gotoUrl;
}
and
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
}
});
});
But the page is doing a form submit when the SearchUSer function being called.I am getting the correct url in the alert.But The page is not loading in the brower
Any Ideas ???
Thanks in advance
if (document.addEventListener) {
document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
document.getElementById('strip').onkeypress = HandleKeyPress;
}
function HandleKeyPress(e) {
switch (e.keyCode) {
case e.DOM_VK_ENTER:
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
}
EDIT due to original Question edit:
all you need is:
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
});
});
edited to reflect comment
Returning false often does the trick.
http://javascript.about.com/library/bldisdef.htm
I have two recommendations. First, use the keydown event instead of keyup (it catches "enter" before submit better). Second, in your SearchUser() function, use window.location instead of window.navigate to go to the other page.
$(document).ready(function() {
$("#frmUserListSearch").keydown(function(event) {
if(event.keyCode == 13){
SearchUser();
return false;
}
});
});
NOTE: Don't forget to remove the "alert()" inside the SearchUser() function as it causes the form to submit before navigating away from the page.
You can do this by using the action attribute of the form, without having to deal with key events, granted that you will later need javascript to take action on the control that submits the form.
<html>
<head>
<script type="text/javascript">
function donothing() {}
</script>
<body>
<form action='javascript:donothing()'>
...
</form>
</body>
</html>

Activating OnBeforeUnload ONLY when field values have changed

What I'm trying to achieve is to Warn the user of unsaved changes if he/she tries to close a page or navigate away from it without saving first.
I've managed to get the OnBeforeUnload() dialog to pop-up... but I don't want it to be displayed at all if the user hasn't modified any field values. For this, I'm using this hidden input field called is_modified that starts with a default value of false and flips to true when any field is edited.
I tried to bind the change event to this is_modified field to try and detect for value change... and only then activate OnBeforeUnload.
$( '#is_modified' ).change( function() {
if( $( '#is_modified' ).val() == 'true' )
window.onbeforeunload = function() { return "You have unsaved changes."; }
});
But from what I figure is that the change() event works only after these 3 steps - a field receives focus, a value is changed and the field looses focus. In case of the hidden input field, I'm not sure how this receiving and loosing focus part works! Hence, the onbeforeunload function is never being activated.
Can anyone suggest a way to maintain a trigger over is_modified?
Thanks.
I had a similar requirement so came up with following jQuery script:
$(document).ready(function() {
needToConfirm = false;
window.onbeforeunload = askConfirm;
});
function askConfirm() {
if (needToConfirm) {
// Put your custom message here
return "Your unsaved data will be lost.";
}
}
$("select,input,textarea").change(function() {
needToConfirm = true;
});
The above code checks the needToConfirm variable, if its true then it will display warning message.
Whenever input, select or textarea elements value is changed, needToConfirm variable is set to true.
PS: Firefox > 4 don't allow custom message for onbeforeunload.
Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=588292
UPDATE: If you are a performance freak, you will love #KyleMit's suggestion.
He wrote a jQuery extension only() which will be executed only once for any element.
$.fn.only = function (events, callback) {
//The handler is executed at most once for all elements for all event types.
var $this = $(this).on(events, myCallback);
function myCallback(e) {
$this.off(events, myCallback);
callback.call(this, e);
}
return this
};
$(":input").only('change', function() {
needToConfirm = true;
});
The following works well in jQuery:
var needToConfirm = false;
$("input,textarea").on("input", function() {
needToConfirm = true;
});
$("select").change(function() {
needToConfirm = true;
});
window.onbeforeunload = function(){
if(needToConfirm) {
return "If you exit this page, your unsaved changes will be lost.";
}
}
And if the user is submitting a form to save the changes, you might want to add this (change #mainForm to the ID of the form they're submitting):
$("#mainForm").submit(function() {
needToConfirm = false;
});
We just use Window.onbeforeunload as our "changed" flag. Here's what we're doing, (using lowpro):
Event.addBehavior({
"input[type=radio]:change,input[type=text]:change,input[type=checkbox]:change,select:change": function(ev) {
window.onbeforeunload = confirmLeave;
}
".button.submit-button:click": function(ev) {
window.onbeforeunload = null;
},
});
function confirmLeave(){
return "Changes to this form have not been saved. If you leave, your changes will be lost."
}
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works For me.
Try your logic in a different manner. Meaning, put the logic for checking the value of the input field in your onbeforeunload method.
window.onbeforeunload = function () {
if ($("#is_modified").val() == 'true') {
return "You have unsaved changes.";
} else {
return true; // I think true is the proper value here
}
};
in IE9 you can use simple return statement (re) which will not display any dialogue box. happy coding..
why not have the onbeforeunload call a function that checks if the values have changed, and if so return the "unsaved changes" confirm?

Categories

Resources