2

I have a small piece of jQuery that I need a bit of help with. Here's what I have:

jQuery:

jQuery(".disableUser").click(function() {
    jQuery(".enableUser").show()
    jQuery(".disableUser").hide();
});

jQuery(".enableUser").click(function() {
    jQuery(".disableUser").show()
    jQuery(".enableUser").hide();
});

HTML:

<tr>
    <td></td>
    <td></td>
    <td></td>
    <td><span class="disableUser">Disable this user</span><span class="enableUser">Enable this user</span></td>
</tr>

.enableUser is set to display:none as default.

As you can see, it is simply hiding or showing an element. My issue is that there are rows in a table, with each row having the same two elements. When I click one row's element it hides or shows all the row's element. I only want it to affect the specific element I am clicking on and not all elements with the same class. I have tried the info found here: http://css-tricks.com/snippets/jquery/click-once-and-unbind/, but I am not sure if I am understanding it or using it correctly.

2
  • post relevant html too, you need to target specific elements regarding the one clicked Commented Aug 2, 2013 at 22:07
  • Thanks, I added the basic html of the row. Commented Aug 2, 2013 at 22:19

2 Answers 2

4

You probably want to find the .enableUser and .disableUser of the current row. this will refer to the clicked element and from there you can traverse the DOM and find the right elements:

jQuery(".disableUser").click(function() {
    jQuery(this).hide().closest("tr").find(".enableUser").show();
});

Have a look at the documentation for .closest and .find for more information. You might also want to read more about event handling.

Sign up to request clarification or add additional context in comments.

3 Comments

@roasted: Of course! Just tweaked it a little since I don't know if both elements are in the same cell. Thanks!
Please see above, I added the basic HTML I will be using. Thanks.
Just commented below on roasted's answer. Both answers work exactly how I wanted it to. Which way is the preferred way of doing it?
1
jQuery(".disableUser").click(function() {
    jQuery(this).hide().siblings('.enableUser').show();
});

jQuery(".enableUser").click(function() {
    jQuery(this).hide().siblings('.disableUser').show();
});

3 Comments

Both of these answers work exactly how I wanted it to. Which answer is the preferred way of doing it?
This one is a little bit optimized but nothing you'll never notice so just choose the one which seems more readable for you and upvote both answers :)
Thanks for your answer, I'm upvoting it for sure. Felix posted his first, so I'll accept his. I'm actually going to use your answer though. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.