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

How do I get the total rows per group with the Janus GridEx for WinForms?

winforms janus gridex

I am using the Janus GridEx (Windows Forms) and would like to export the contents to Excel. We have used the export functionality that Janus has built in before, but especially with hierarchical g...

Absurd values to main(int argc, char** argv)

windows msvcrt

I had on old C++ project starting a Console-application.

Passing options in autospec with Cucumber in Ruby on Rails Development

ruby-on-rails ruby rspec cucumber autotest

I always run autospec to run features and RSpec at the same time, but running all the features is often time-consuming on my local computer. I would run every feature before committing code.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.