Reputation: 175
I have multiple input checkboxes wrapped up in p tags <p><input type="checkbox" /></p>
. I'm trying to change the background-color
of the P tag when the checkbox is :checked
The problem I'm having is that all of the <p> </p>
tags background colors are changing at the same time. I only want the current paragraph tag background-color
to change.
HTML
<p>
<input type="checkbox" />
<label>Animals & Pets</label>
</p>
<p>
<input type="checkbox" />
<label>Business & Finance</label>
</p>
<p>
<input type="checkbox" />
<label>Auto's & Cycles</label>
</p>
CSS
.highlight { background-color: #DDD; }
jQuery
$(document).ready(function() {
$('input').click(function() {
if ($(this).is(':checked')) {
$('p').addClass('highlight')
} else {
$('p').removeClass('highlight')
}
});
});
Upvotes: 1
Views: 1320
Reputation: 318182
You can target the parent paragraph with closest()
, and use toggleClass()
to toggle the class, and the change
event would be the proper event to listen for when changing a checkbox :
$(document).ready(function() {
$('input').on('change', function() {
$(this).closest('p').toggleClass('highlight', this.checked);
});
});
Upvotes: 4
Reputation: 2205
Use this
isntead of just p
. Then get its parent using .parent()
$(document).ready(function() {
$('input').click(function() {
if ($(this).is(':checked')) {
$(this).parent().addClass('highlight')
} else {
$(this).parent().removeClass('highlight')
}
});
});
Upvotes: 0
Reputation: 219920
Use closest
:
$('input').change(function () {
if ( this.checked ) {
$(this).closest('p').addClass('highlight');
} else {
$(this).closest('p').removeClass('highlight');
}
});
You can also make this a little shorter by using toggleClass
:
$('input').change(function () {
$(this).closest('p').toggleClass('highlight', this.checked);
});
Upvotes: 4