Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery : Assigning multiple id's to do the same function.

A rather simple question that I feel has a simple solution to, but can't seem to think of the right way of going about solving.

I have a set of buttons laid out in a 3 x 3 format, that I want to change attributes of when clicked, but independently. I gave them all the same class, but differentiated them using id's.

Is there a way to write, in one line for a group of ID's to do the same thing? Or do I have to redundantly write out each button's call.

I guess to put it simply, can I write

 $('.ready').click(function(){
   if('.ready'.is('#7') || '.ready'.is('#8') || '.ready'.is('#9')){
      execute code.
   }
 });

Any help would be greatly appreciated!

like image 967
Peter Alexander Kamenkovich Avatar asked Aug 19 '26 19:08

Peter Alexander Kamenkovich


2 Answers

You don't need the class .ready selector since ids are unique enough to target as selectors.

 $('#7,#8,#9').click(function()
{
    // do stuff
});
like image 106
DinoMyte Avatar answered Aug 21 '26 10:08

DinoMyte


You can simply do

var pair1 = "#7, #8, #9";
var pair2 = "#2, #3, #4";
$('.ready').click(function(){

   if($(this).is(pair1)){
      execute code.
   }

   else if($(this).is(pair2)){
      execute some other code.
   }

});
like image 44
void Avatar answered Aug 21 '26 08:08

void



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!