4

The function closest to jQuery

 3 years ago
source link: https://www.codesd.com/item/the-function-closest-to-jquery.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

The function closest to jQuery

advertisements

Alright I know that the .closest() have been discussed before, but I have been searching, and I still can't get it working.

The situation is this. I have a table with some checkboxes and labels. Now when a checkbox is checked I want a div to appear, and disappear when unchecked. Keep in mind that this is dynamic PHP code.

I have got it working this far, but the current issue is that all the message divs appear instead of just the appropriate one.

$('[name^="check"]').click(function() {
    $(".message").toggle(this.checked);
});

Now the checkboxes have names such as check1, check2 and check3. A matter of how many that is generated.

I have tried to play around with different this(), parent() and closest() functions in my attempt to select just one of the divs, but I can't get it working.

Thank you for your attention.

Edit:

The HTML that is rendered look somewhat like this (simplified)

<div style="float: left;">
<input type="checkbox" id="check1" name="check1" value="1"><label for="check1">Label for check1</label></div>
<div class="message" style="display: none; ">FOO</div>

<div style="float: left;">
<input type="checkbox" id="check2" name="check2" value="2"><label for="check2">Label for check2</label></div>
<div class="message" style="display: none; ">FOO</div>


This should work for you, with your provided markup.

$('[name^="check"]').click(function() {
    $(this).parent().next(".message").toggle(this.checked);
});

Side node: you could improve your selector performance by using input[name^="check"] so jQuery does not need to iterate through all elements.

Code example on jsfiddle.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK