1

I am using following form and submit button in my dynamic html page.

<form method=\"post\" class=\"my-form\" >

and

<input type=\"submit\" name=\"submitButton\" value=\"Submit\" id=\"button1\" />

What I am trying to do is when a particular input is provided by user, then display an alert box asking if user wants to submit the change or just stay on the same page without submitting the change.

I can display the alert box (with help from stackoverflow members) but along with window.alert what I should add to JavaScript so the form is not submitted if user clicks "cancel" on window.confirm and the form is submitted if user clicks "ok" on window.confirm?

JavaScript example is at fiddle

$(document).on('input', '.my-input', function(){
    $(this).closest('form').addClass('changed');
});

$(document).on('submit', '.my-form', function(e){
    if($(this).hasClass('changed')){
     var x=window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
    if (x)
        window.alert("Thresholds changed!")
    else
        window.alert("Thresholds not changed!")
    } 
    $(this).removeClass('changed');
    e.preventDefault();
});
isherwood
  • 58,414
  • 16
  • 114
  • 157
300
  • 965
  • 1
  • 14
  • 53

2 Answers2

4

You just need to change your logic so that preventDefault() is only called when the user declines the confirm box. Try this:

$(document).on('submit', '.my-form', function (e) {
    if ($(this).hasClass('changed')) {
        var allowSubmit = window.confirm("You have set a unique threshold for one or more states below. Are you sure you want to reset them all?")
        if (!allowSubmit) 
            e.preventDefault()
    }
});

Example fiddle

If you click 'OK' you'll see that the form is submit (and a warning from jsFiddle to use a POST request - but that's normal), whereas clicking 'Cancel' does nothing.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you Rory, it works as I was looking for. There is one doubt though: If I enter a value and click submit button, I see the alert window with "ok" and "cancel" buttons. If I click cancel then page remains as it is and form is not submitted (which is as expected). But if I click on submit again, then the form gets submitted directly without an alert window with "ok" and "cancel" buttons being displayed. How can I ensure that alert window is displayed every time submit is clicked (and if value in the text box was changed) – 300 Sep 04 '15 at 18:32
  • 1
    That's because you need to remove the `removeClass()` line - I updated my answer for you – Rory McCrossan Sep 04 '15 at 19:15
0

You can also return false in your submit function handler, it should work. Check this question for an example.

avenet
  • 2,894
  • 1
  • 19
  • 26