Will
Will

Reputation: 544

Change Color of Checkbox List Item onChange

I have a list of checkboxes + labels. I want the background color of the list item to change when the checkbox is selected. Currently, when the checkbox is selected, the entire list changes background color, whereas I only want the background-color of the individual item to change. Thanks for the help!

Code:

names = ["Dave","Bob","Chuck"];
var numberOf = names.length; 
//Log the number of players and their names to the console.
console.log("You have " + numberOf + " recent players, and their names are " + names);
//Players List
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
    text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
    }
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;

//Changes background of currently selected playe
$('input.playerCheckbox').on('change', function(event) {
$('li.playerListItem').css('backgroundColor', 'rgba(255,102,51,0.15)');
});

});

Upvotes: 0

Views: 875

Answers (4)

James Hibbard
James Hibbard

Reputation: 17735

You can do it like this:

$('input.playerCheckbox').on('change', function(event) {
  $(this).closest("li").css('backgroundColor', 'rgba(255,102,51,0.15)');
});

It might also be worth adding that this will not remove the background colour when the checkbox is deselected. Therefore I would just use a class that you can remove and apply as appropriate.

Upvotes: 1

Feddman
Feddman

Reputation: 101

use the 'this' keyword on the event listener.

$('input.playerCheckbox').on('change', function(event) {
  // 'this' below refers to the clicked element. the parents() function selects only its parent's <li>   

  $(this).parents('li').css('backgroundColor', 'rgba(255,102,51,0.15)'); 
});

Upvotes: 1

adeneo
adeneo

Reputation: 318182

Not enough jQuery

$('#recentPlayersContainer').append(
    $('<ul />').append(
        $.map(["Dave","Bob","Chuck"], function(player) {
            var check = $('<input />', {
                'class' : 'playerCheckbox',
                type    : 'checkbox',
                on      : {
                    change : function() {
                        $(this).closest('li')
                        .css('backgroundColor', this.checked ? 'rgba(255,102,51,0.15)' : "");
                    }      
                }
            }),
                lbl = $('<label />', {text : player}),
                li  = $('<li />', {'class' : 'playerListItem'});

            return li.append( lbl.prepend( check ) );
        })
    )
);

FIDDLE

Upvotes: 1

Seva Arkhangelskiy
Seva Arkhangelskiy

Reputation: 685

$('input.playerCheckbox').on('change', function(event) {
    $(this).closest('li.playerListItem').css('backgroundColor', 'rgba(255,102,51,0.15)');
});

Upvotes: 1

Related Questions