How can I disable multiple links with jQuery?

I have the following HTML:

<a title="Login" data-href="/MyAccount/Access/Login" 
   data-title="Admin" data-entity="n/a" 
   id="loginLink" class="nav-button dialogLink"><b>Login</b></a>

<a title="Register" 
   data-href="/MyAccount/Access/Register" 
   data-title="Admin" data-entity="n/a"
   id="registerLink" class="nav-button dialogLink"><b>Register</b></a>

When a user clicks on the #loginLink or #registerLink I would like to disable the link and call a dialog script. I created the following function:

$("#loginLink, #registerLink")
    .click(function () {
        $('#loginLink').prop('disabled', true);
        $('#registerLink').prop('disabled', true);
        dialog(this);
    });

It calls the dialog correctly but doesn't disable the links and if I click the buttons more than once it calls up more than one dialog box. Is there something I am doing wrong? I can't see why it would not work.

Answers


If you want to bind and unbind events at any time, store the code in a function, then you can use namespaced events to associate the event with that function.

function dlog(e) {
  e.preventDefault();
  dialog(this);
}

var $els = $("#loginLink, #registerLink");

$els.on('click.dlog', function(e){ dlog(e) }); // bind
$els.off('.dlog'); // unbind

Edit: Another option would be to use one() which attaches the event just once, then you can attach the event again when the dialog is closed.

$els
  .one(function(e) { dlog(e) })
  .dialog({
     beforeClose: function() { 
       $els.one(function(e) { dlog(e) });
     }
  });

You have to use jQuery's on() and off() methods to bind/unbind events. Setting disabled property have no effects on links, click events will still be fired.

Here you can find a description and demo: http://api.jquery.com/off/


Need Your Help

jQuery UI Selectable, can't access items during selecting

jquery jquery-ui

I've got some piece of code with jQuery UI Selectable implementation. Just like this:

MySQL performance boost after create & drop index

mysql sql caching indices

I have a large MySQL, MyISAM table of around 4 million rows running in a core 2 duo, 8G RAM laptop.

How to get the onfocus event to fire for checkbox in firefox and chrome

javascript asp.net visual-studio-2010 firefox web-applications

In IE i am using an onfocusin event and everything works as expected for the checkbox however onfocusin only works with IE and not other browsers. Also the onfocus doesn't work for checkbox's eithe...