Balabeque Balabeque - 5 months ago 20
jQuery Question

How to address an exact element (from multiple ones with the same class) on the related checkbox action?

I have a small table-like widget that has multiple stripes (

<div class="widget_stripe">
) in it, each of which have a name (title) and a checkbox. The HTML structure is as follows:

<div class="widget_stripe">
<div class="col-sm-10 activity_name_holder">
<p class="activity_name">Send the annual report to Mr. Smith</p>
</div>
<div class="col-sm-2 status_checkboxes_holder">
<form action="#" class="allow_mediacontacts_form">
<p>
<input class="t3t" type="checkbox" id="activity8" />
<label class="l3l" for="activity8"></label>
</p>
</form>
</div>
</div>


So what I want to do is to change the font-weight (from 700 to 400) of the text inside
<p class="activity_name>
, so I'm adding a special class when the checkbox is checked.

var activityName = $('p.activity_name');
$("input.t3t").click(function() {
if($(this).is(":checked")) {
$(activityName).addClass('checked_name');
} else {
$(activityName).removeClass('checked_name');
}
});


However, as you can see, it will simply fire this action an all the
<p>
s with this class, and I cannot figure out how to address that exact
<p class="activity_name>
that is situated in the same
<div class="widget_stripe">
that the checkbox. How can I achieve this behavior?

Thanks in advance!

Answer

Use this and navigation to apply the class only to the selected item

if ($(this).is(":checked")) {
  $(this).closest("div.widget_stripe").find("p.activity_name").addClass('checked_name');
} else {
  $(this).closest("div.widget_stripe").find("p.activity_name").removeClass('checked_name');
}
Comments