Roxx
Roxx

Reputation: 3996

Event on ok cancel button in JavaScript

I am stuck with a small issue.

<input class="btn btn-home" type="submit" name="discard" id="discard" onclick="return confirm('Are you sure you want to discard changes?')" alt="Discard" value="Discard Changes"/>
$('document').ready(function(){
    var subm = "";
    $('input[type="submit"]').click(function(e) {
        subm = e.target.id;
        if(subm == 'discard')
            window.location = "http://www.weblink.com/manager.php";
    })
});

When user click on button a confirmation box will appear with ok cancel. When user click on ok it will redirect to other page and if user click on cancel then it will stay on this page.

Problem is it is redirecting if user click on cancel. I don't want to redirect the page if cancel button clicked.

Upvotes: 0

Views: 4292

Answers (3)

Brajendra Swain
Brajendra Swain

Reputation: 355

You need to remove the inline script,

and the modification to the code should be something like the below -

$('document').ready(function()
{
  var subm = "";
 $('input[type="submit"]').click(function(e) {
   var isConfirmed = confirm('Are you sure you want to discard changes?');
   if(isConfirmed){
     subm = e.target.id;
     if(subm == 'discard'){
       window.location = "http://www.weblink.com/manager.php";
    }
   }
 });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <input class="btn btn-home" type="submit" name="discard" id="discard"   alt="Discard" value="Discard Changes"/>

Upvotes: 0

bhavya_w
bhavya_w

Reputation: 10107

Put confirm dialog inside onsubmit listener instead. No need to use click listener.

<form onsubmit="return confirm('whatever your confirmation message')">

    <input class="btn btn-home" type="submit" name="discard" value="Discard Changes"/>
</form>

Upvotes: 0

Mitya
Mitya

Reputation: 34598

Two problems here:

  • You're trying to combine inline and external JS, which is always a bit messy
  • You're not suppressing the native behaviour of submit buttons, which is to submit a form (which I assume you have in your HTML, even though it's not shown). In fact, you don't even need the button to be of type submit.

HTML:

<button class="btn btn-home" name="discard" id="discard">Discard Changes</button>

JS:

$('#discard').on('click', function(evt) {
    evt.preventDefault(); //don't submit the form, which a button naturally does
    if (confirm('Are you sure you want to discard changes?'))
        location.href = 'http://www.weblink.com/manager.php'; //redirect only on confirm
});

Upvotes: 1

Related Questions