js999
js999

Reputation: 2083

The best way to generalise a code for toggling the disabled attribute

The following code (*) for toggling the disabled attribute beetween two buttons works and you can check it at http://jsfiddle.net/cNSVX/3/.

I was wondering what is the best way to generalise this code in order to attach this behaviour to a couple of buttons.
Something like the following.

body.onload(togglingButton(elem1, elem2));

$('#filterOpened').click(function() {
    $('#filterOpened').attr('disabled', 'disabled');
    $('#filterClosed').removeAttr('disabled');
});

$('#filterClosed').click(function() {
    $('#filterClosed').attr('disabled', 'disabled');
    $('#filterOpened').removeAttr('disabled');
});

function togglingButton (elem1, elem2) {
    if (elem2.attr('disabled')) {
        elem1.attr('disabled', 'disabled');
        elem2.removeAttr('disabled');
   } else {
        elem2.attr('disabled', 'disabled');
        elem1.removeAttr('disabled');
   } 
};
​

Upvotes: 1

Views: 76

Answers (2)

jackwanders
jackwanders

Reputation: 16050

One simple way to do this would be to use jQuery's .data() function to link the two elements, then assign a single event handler to both:

function disableToggle(el1,el2) {
    el1.data('partner',el2);
    el2.data('partner',el1);

    el1.add(el2).on('click',function(){
        $(this).prop('disabled',true);
        $(this).data('partner').prop('disabled',false);
    });
}

$(function(){
    var opened = $('#filterOpened');
    var closed = $('#filterClosed');

    disableToggle(opened,closed)
});

I've created a demo:

jsFiddle DEMO

Upvotes: 0

wirey00
wirey00

Reputation: 33661

You can do it like below with jQuery. Also if you are using jQuery 1.6+ then you should be using .prop() to toggle your disabled property.

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The prop method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.

​$('button').click(function(){ //<---  attaches click to all button's
      $(this).prop('disabled',true);  //<-- only disable the clicked button
      $('button').not(this).prop('disabled',false);  //<-- all button's but the clicked one should be enabled
});​​​

here's an example fiddle http://jsfiddle.net/cNSVX/5/

If you are planning on excluding some buttons out of the toggling it would be a good idea to give them a class so you can select the ones you need/don't need easier

Upvotes: 1

Related Questions