Gui February 2016

ToggleClass jQuery for only ONE element of li

I am trying to add a background color to a checkbox and its text after the user clicks on it (checking it). In here though, it adds in all of my list not only the LI clicked.

HTML

<li class="parent_category">
  <ul>
      <li class="behind">
              <label>
                  <input type="checkbox">
                  Text3 Text Text
              </label>
       </li>
       <li class="behind">
              <label>
                  <input type="checkbox">
                  Text2 Text Text
              </label>
       </li>
       <li class="behind">
              <label>
                  <input type="checkbox">
                  Text1 Text Text
              </label>
       </li>
       <li class="behind">
              <label>
                  <input type="checkbox">
                  Text4 Text Text
              </label>
       </li>
  </ul>
</li>

jQuery

define([], function(){
  var main = function(data, options) {

    $(function () {
      $(".parent_category").click(function() {

        $(this).toggleClass("selected");
      });

      $("label.parent_category").click(function(e) {

        $(e.currentTarget).toggleClass("background");
      });
    });
    console.log("Select Recommended loaded");
  }
  return main;
});

And then the Sass file

.parent_category
float: right
margin: 15px
&.selected
  border: 4px solid #ffe400
  ul
      width: 100%
      padding: 0px
      li
          padding-left: 20px
          border-bottom: 1px solid #CCCCCC
          display: block
          &:last-child
              border-bottom: none

.behind
display: none

.background
background-color: #CCCCCC
width: 100%

So what I'm trying to achieve is > I want the background of one li (the whole row) to go gra

Answers


Denys Konoplin February 2016

I didn't get, why you add click event on this element $("label.parent_category") - you don't have such in your html structure.. Is it a typo?

Try this variant:

$('.parent_category input:checkbox').on('change', function(){
        var $checkbox = $(this);
        $checkbox.closest('label').toggleClass('background', $checkbox.is(':checked'));
    });

instead of

$("label.parent_category").click(function(e) { $(e.currentTarget).toggleClass("background"); });


Marc February 2016

Try to replace :

$("label.parent_category").click(function(e) {

By :

$(".parent_category label").click(function(e) {

I think you made a mistake with your selector.


CodingWithSpike February 2016

You can use the .on function with a selector as the 2nd parameter:

$('.parent_category').on('click', 'li', function (clickEvent) {
    // ...
});

This will add 1 click handler to the DOM that reacts to each li in .parent_category.

Post Status

Asked in February 2016
Viewed 1,263 times
Voted 9
Answered 3 times

Search




Leave an answer