Billy Billy - 5 months ago 7
jQuery Question

How to target more than one element while using operators for an onclick event

Here I would like to target more than one element for an onClick event while also disabling all buttons apart from the one that has been clicked.

So far I have this:

$("#elementone", "elementtwo, #elementthree").on('click', function(){
if($(this).is(':checked')){
$('#elementone, #elementtwo, #elementthree').attr('disabled', true);
}
});


The code below does what I want however I was hoping there would be a more elegant way to achieve this?

$("#elementone").on('click', function(){
if($(this).is(':checked')){
$('#elementtwo, #elementthree').attr('disabled', true);
}
});

$("elementtwo").on('click', function(){
if($(this).is(':checked')){
$('#elementone, #elementthree').attr('disabled', true);
}
});

$("#elementthree").on('click', function(){
if($(this).is(':checked')){
$('#elementone, #elementtwo').attr('disabled', true);
}
});

Answer

Use class instead of id That is, place a class named "element" (or any other valid class name) on the three buttons. Then you can use:

var $elements = $('.element');
$elements.click(function() {
    if ($(this).is(':checked')) {
       $elements.not(this).prop('disabled', true);
   }
});

Notes:

  1. The call to .not(this) removes the currently clicked button from the set.
  2. You should also use .prop(), instead of .attr() to disable the buttons.
  3. If these are <input type="checkbox"> elements, it would be better to use the change event, instead of the click event.
Comments