0

How to stop a HTML page from redirecting using Javascript when the user clicks a link if a condition is false/true? To be specific, the link is something like this:

<a href = "something.html">
<li class ="num" id="day1" onclick = "return checkDate(1)"></li>
<li class ="num" id="day2" onclick = "return checkDate(2)"></li>
<li class ="num" id="day3" onclick = "return checkDate(3)"></li> 
</a>

In my javascript file, I'll have something like:

Function checkdate(a){
if(a = 3){ don't redirect }

}

Just I don't know what to put to and all the google results for the problem are confusing. Thanks in advance.

Kay
  • 85
  • 11

4 Answers4

1
function checkdate(a){
if(a == 3){ return false; }

}
vusan
  • 5,221
  • 4
  • 46
  • 81
  • The reason why this works is explained here: http://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-an-onclick-event – terite Jun 14 '13 at 18:25
1

Try this:

function checkdate( a ) {
    // block
    if ( a == 3 )
       return false;

    // your code to redirect if a != 3
}
0

A couple of things. First, your markup is invalid. <li> tags need a <ul> or <ol> parent. Also, you're declaring a Function. JavaScript is VERY case sensitive, you'll need to declare this as function. I would modify your HTML to:

<li class ="num" id="day1" onclick = "checkDate(1)"></li>
<li class ="num" id="day2" onclick = "checkDate(2)"></li>
<li class ="num" id="day3" onclick = "checkDate(3)"></li> 

JS:

function checkdate(a){
    if (!a == 3) {
        //redirect
    }

    return false;
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

I could suggest something here using an onUnload event, but I think the simpler solution here is to have the actual "linking" code be in the <li>'s onclick event. I'm not quite sure if the other suggestions here work - you will "cancel" the onclick event for the <li>, but not for the <a>.

Here's my try. If you're using JQuery or something, there are other ways you can shorten it.

function gotoSomething(num) {
    if (checkdate(num)) {
        window.location = "something.html";
    }
}

HTML:

<a href = "#">
<li class ="num" id="day1" onclick = "gotoSomething(1)"></li>
<li class ="num" id="day2" onclick = "gotoSomething(2)"></li>
<li class ="num" id="day3" onclick = "gotoSomething(3)"></li> 
</a>
Katana314
  • 8,429
  • 2
  • 28
  • 36
  • Hm. If "return false" worked for other people, then I obviously did something wrong in my test - when I put that in, it wasn't preventing the link. I guess this one can be ignored. – Katana314 Jun 14 '13 at 18:24