Fiv
Fiv

Reputation: 175

Select one element at a time using jquery

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 &amp; Pets</label>
</p>

<p>
  <input type="checkbox"  />
  <label>Business &amp; Finance</label>
</p>

<p>
  <input type="checkbox" />
  <label>Auto's &amp; 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

Answers (3)

adeneo
adeneo

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);
    });
});

FIDDLE

Upvotes: 4

Jude Duran
Jude Duran

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

Joseph Silber
Joseph Silber

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

Related Questions