Satch3000
Satch3000

Reputation: 49364

JQuery onclick condition stop link?

I have a link:

Link

using::

$('#myID').click(function(){
    if($("#myCheckbox").is(":checked")) {
        alert('Yes it is...'); //continue as normal
    }
    else {
        alert('Not checked');
        //exit do not follow the link
    }

...

so is //exit do not follow the link possible?

Upvotes: 6

Views: 7378

Answers (6)

Matt K
Matt K

Reputation: 6709

You can pass in the event, and override the default behavior with the following:

$('#myID').click(function(e) {
    e.preventDefault();
    //exit do not follow the link
});

Upvotes: 1

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You can use event.preventDefault()

Let your click-function receive the event as a parameter. Then you can do event.preventDefault() when you don't want to follow the link.

$('#myID').click(function(event){
   if($("#myCheckbox").is(":checked")) {
       alert('Yes it is...'); //continue as normal
   }
   else 
   {
       alert('Not checked');
       //exit do not follow the link
       event.preventDefault();
   }
});

Upvotes: 2

epoch
epoch

Reputation: 16595

just use return false; when you want to stop the action at a specific point

Upvotes: 3

Pavan
Pavan

Reputation: 4329

Return false in your else condition.

$('#myID').click(function(){ 
if($("#myCheckbox").is(":checked")) { 
    alert('Yes it is...'); //continue as normal 
} 
else { 
    alert('Not checked'); 
    return false;
} 

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Try using event.preventDefault()

$('#myID').click(function(e) {
    if ($("#myCheckbox").is(":checked")) {
        alert('Yes it is...');
    }
    else {
        alert('Not checked');
        e.preventDefault(); // this prevents the standard link behaviour
    }
}

Upvotes: 8

karim79
karim79

Reputation: 342625

Simple:

$('#myID').click(function (e) {
    ...
} else {
    alert('Not checked');
    e.preventDefault();
}

You can also use return false, but this will also stop the propagation of the click event (which might be undesired).

Upvotes: 3

Related Questions