0

I have a buttons like these:

<button class="sOne sTwo sThree addUser">Click Me</button>
<button class="sOne sTwo sThree delUser">Click Me</button>
<button class="sOne sTwo sThree blockUser">Click Me</button>

I need to detect only the class addUser because in my jQuery I do:

$('.addUser,.delUser,.blockUser').click(function() {
var act = $(this).attr('class');
switch (act)
case 'addUser':
case 'delUser':
case 'blockUser':
});

Problem is, I get the entire class in there which is: sOne sTwo sThree addUser, and all my script fails.

How can I detect only the class addUser or delUser etc.

1

2 Answers 2

1

You could use hasClass():

$('.addUser,.delUser,.blockUser').click(function() {
    if ($(this).hasClass('addUser')) {
        //do something
    }
});

It might be worth evaluating whether you could give each element it's own click handler though, if all the code for each is different.

2
  • It might be worth evaluating whether you could give each element it's own click handler though, if all the code for each is different. You mean... ?
    – jmenezes
    Commented Oct 23, 2013 at 15:11
  • Perhaps you don't have the ability to change the way the code is generated, but you'd have a much easier time leaving class to govern the styling or common functions, and using a unique ID property for each to which you can bind unique functions. Commented Oct 23, 2013 at 15:17
0

Insted of switch use if and else if like below,

$('.addUser,.delUser,.blockUser').click(function() {
  var $this = $(this);
  if ($this.hasClass('addUser') {
       //code for addUser
  } else if ($this.hasClass('delUser') {
       //code for delUser
  } else if ($this.hasClass('blockUser') {
       //code for blockUser
  }
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.