views:

2349

answers:

7

How would I disable all links with the button class after they are clicked once? I'd like to be able to do this in one place, and not have to change all of them individually.. any ideas?

So far I got this:

$("a.button").click(function() { $(this).attr("disabled", "disabled"); });
$("a[disabled]").click(function() { return false; });

but the second event isn't firing..

+2  A: 

Yeah, set a value to keep track of this:

$("a").click(function (){
  if( $(this).data("clicked") ){
    return false;
  }
  $(this).data("clicked", true);
  return true;
});
Seb
+1  A: 

create a JS - include it on every page (or in your masterpage if you've got one.)

I think something like

$(document).ready(function(){
  $('.button').click(function(){
    $('.button').click(function(e) {
      e.preventDefault();

    });
  }
}
Paul
+1  A: 
$("a.button").bind('click', function() { $(this).attr("disabled", "disabled"); });
$("a[disabled]").live('click', function() { return false; });

Does it. First line binds to all a-element with class button a function which sets (btw invalid for a-elements) disabled attribute to disabled.

Second function uses jQuery live event rebinding to bind "disabling" function to all future instances of a-elements which have and attribute disabled

Check jQuery Event documentation for more in-depth info on the two used functions if you want

jitter
+1  A: 

Events are only bound on document.ready, you should handle this with a .live event:

$("a.button").live("click", function() { $(this).attr("disabled", "disabled"); });
$("a[disabled]").live("click", function() { return false; });
Mike Robinson
+4  A: 

This is what I would try:

$("a.button").one("click", function() {
    $(this).click(function () { return false; });
});

Bind all the links with class "button". Run the anonymous function only once (hence "one"), which rebinds the link to return false.

If you want to keep it looking more like what you have, try this:

$("a.button").click(function() { $(this).attr("disabled", "disabled"); });
$(document).click(function(evt) {
     if ($(evt.target).is("a[disabled]"))
          return false;
});
Adam
one() is neat! new to me. Nice solution.
artlung
+1  A: 

You could also just throw a class on the anchor tag and check on click:

$('a.button').click(function(){ 
  if($(this).hasClass('clicked')) return false;
  else { 
    $(this).addClass('clicked'); 
    return true;
  }
});

With the class, you can do some extra styling to the link after the first click.

borkweb
A: 
$('a.button').bind('click', function(){
    alert('clicked once'); // for debugging
    // remove all event handlers with unbind()
    // add a new function that prevents click from working
    $(this).unbind().bind('click', function(){
     alert('clicked a 2nd time or more'); // for debugging
     return false;
    });
});
artlung