Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 829
Satch3000 Avatar asked Jan 09 '12 14:01

Satch3000


People also ask

How to disable the link in jQuery?

Description: The basic disable link is using removeAttr( 'href' ) to disable the href link. The “jquery disable link” is the button to be used for deactivating the web link.

How to prevent href click?

To disable href if onclick is executed with JavaScript, we call preventDefault to stop the default navigation action. document. getElementsById("ignore-click"). addEventListener("click", (event) => { event.

How would you stop a link from causing navigation when clicked?

One way you can prevent navigation is to implement an click / onclick JavaScript event handler and return false from it. Alternately you can use event. preventDefault() inside the click event's event object passed into the handler too.

How do I turn off click events?

To disable the click event on an element, we can use the pointer-events property. Simply set the pointer-events property to none to disable the click event on any element that you want. In the following example, we have disabled the click event for a button by simply setting its pointer-events property to none .


2 Answers

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
    }
}
like image 111
Rory McCrossan Avatar answered Sep 25 '22 15:09

Rory McCrossan


Simple:

$('#myID').click(function (e) {
    ...
} else {
    alert('Not checked');
    e.preventDefault();
}
  • http://api.jquery.com/event.preventDefault/

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

like image 43
karim79 Avatar answered Sep 22 '22 15:09

karim79