views:

62

answers:

2

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?

+6  A: 

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
});
lonesomeday
lonesomeday - If you're going to place the `.delegate()` on the `<body>`, you might as well just use `.live()` since you're not really gaining any efficiency.
patrick dw
@Patrick (1) `live` is always less efficient, because it does an unnecessary original selection; (2) `delegate` has more logical syntax, IMO.
lonesomeday
+1 With regard to the logical syntax, I totally agree. I think I could consider that a compelling enough reason to use `.delegate()` as you did. With regard to the original selection, that's an excellent point that I hadn't considered. I stand entirely corrected. :o)
patrick dw
+1  A: 

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.

patrick dw