1

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

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="return OnClickNextPage();">Test</a>

Thank you

Tuan Pham
  • 49
  • 1
  • 8

4 Answers4

1

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

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage();">Test</a>

Try like this

 <a href="#" onclick="OnClickNextPage();">Test</a>

function OnClickNextPage(e){

   e.preventDefault();
    var result = confirm("Are you sure ?");
      if (!result) {
        return false;
      } else {
         window.location.href = [[Your URL Here]]
      }
 }
Abhinav
  • 1,202
  • 1
  • 8
  • 12
  • 1
    As it is, this doesn't answer the question, since in the original code, the event object is not passed. Also if a user clicks OK in the confirm box, the function is not supposed to prevent the default action. – Teemu Dec 03 '19 at 10:31
  • @user7417866 this answer not work for me, page still load :(( – Tuan Pham Dec 03 '19 at 10:51
  • @TuấnPhạm Try Edited Solution – Abhinav Dec 03 '19 at 11:19
1

Instead of returning false you have to prevent the default beahaviour of the event with preventDefault() function. Here is the code

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage();">Test</a>
function OnClickNextPage(event){
  var result = confirm("Are you sure ?");
  if (!result) {
     event.preventDefault();
   }
 }
1

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

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="OnClickNextPage(event);">Test</a>

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'
}
hoangdv
  • 15,138
  • 4
  • 27
  • 48
0

JS

  function OnClickNextPage(e){

          console.log('after prevent')
          var result = confirm("Are you sure ?");
          if (!result) {
e.preventDefault();
            return false;
           }
         }

HTML

<a href="http://localhost" data-ajax="?link1=saved-posts" onclick="return OnClickNextPage(event);">Test</a>
Damodhar
  • 1,219
  • 8
  • 17