Lorenzo
Lorenzo

Reputation: 29427

Disabling Hyperlinks

Some hyperlinks on my page have reasone to be enabled only when an element is selected inside a grid control.

I have the chance to injects some code when a row is selected on the page and I would like to enable/disable these hyperlinks using jquery code.

Any advice?

Upvotes: 1

Views: 273

Answers (2)

user113716
user113716

Reputation: 322582

It would depend a little bit on how the row is selected.

This example assumes that a click on a <a> with the class .select inside the <tr> will disable all links in the row (except the .select link) that have an href attribute.

$('#myTable tr a.select').click( function() {
    $(this).closest('tr').find('a:not(.select)[href]').addClass('disabled');
});

So each of the links in the rows that have a .click() handler should first check to see if it has the .disabled class before firing its code.

$('#myTable tr a.someClass').click(function( e ) {
      // sounds like you want these either way?
    e.preventDefault();
    e.stopPropagation();
    if( !$(this).hasClass('disabled') ) {
        // run code when not disabled
    }
});

Nice thing about using a class for this is that you can add CSS to that class in order to give visual cues to the user that the link is disabled.

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 238035

It would be easier not to disable them, but merely to prevent them doing what they automatically do. I would do this using $().delegate:

$(document.body).delegate('a', 'click', function(e) {
    if ($(this).is('.disabled')) { // or whatever logic here
        e.preventDefault();
    }
});

You could use any logic in the conditional clause, e.g. checking for the existence of other elements on the page, checking a configuration variable, etc.

Edit This won't reliably work if there are handlers higher up the tree that stop propagation. If you have got loads of functions doing things to propagation, your easiest solution would be to do the conditional checking at the start of each function:

$('#your_link').click(function(e) {
    if (logic) {
        e.stopPropagation();
        e.preventDefault();
    };

    // the rest of your function here
});

Upvotes: 6

Related Questions