Dobrikella
Dobrikella

Reputation: 145

javascript/html - change color of checkbox text when box if checked by user

I'm trying to change the color of my checkbox text label when the user checks the box and clicks the toggle button. I looked up other examples and tried to make my own solution below but it doesn't work when I check the boxes I want to check and click the button. I was wondering why?

function addItem() {
  var input = document.getElementById("textbox");
  var wrapper = document.getElementById("checklist_items");
  if (input.value.trim() != "") {
    var new_element = document.createElement("DIV");
    new_element.innerHTML = '<input type="checkbox"> ' + input.value;
    wrapper.appendChild(new_element);
    document.getElementById('textbox').value = '';
  } else {
    alert("You must enter at least 1 character.");
  }
}

function toggleItem() {
  var chkbx = document.querySelectorAll('checklist_items');
  if (chkbx.checked) {
    document.getElementById('checklist_items').style.color = "red";
  } else {
    document.getElementById("checklist_items").style.backgroundColor = "transparent";

  }

}
<html>
    <head>
	    <title>Checklist</title>
    </head>
    <body>
	    <div><h1>My to-do list</h1></div><br />
	    <div id ="myCheckList">Enter an item:</div>
	    <div>Type something: <input type="text" id="textbox"></input></div>
	    <input type="button" id="addBut" value = "Add item" onclick="addItem()"/>
	    <input type="button" id="toggleBut" value = "Toggle highlight" onclick="toggleItem()"/>
	
	    <script src="addHandler.js"></script>
	    <div id="checklist_items"></div>
    </body>
</html>

How my program works is the user enters a bunch of text in the textbox and clicks the add button, which creates a checkbox for their input. I want the name of their input beside the checkbox to change colors when I check it and click the toggle button.

Upvotes: 1

Views: 749

Answers (2)

chofre117
chofre117

Reputation: 15

var chkbx = document.querySelectorAll('checklist_items') needs to be var chkbx = document.querySelectorAll('#checklist_items') or var chkbx = document.getElementById('checklist_items'). querySelectorAll takes CSS selectors as arguments, which are either html elements or class or id names with the corresponding prefix. IDs have the prefix # and classes have the prefix .

Upvotes: 1

Kamil Waniczek
Kamil Waniczek

Reputation: 67

Using JQuery:

$(".your_checkbox_class").change(function () {
    if ($(this).is(':checked')) {
        $(this).css("background-color","your_color_here");
    }
};

EDIT: You should also give this checkbox class or id

EDIT 2:

document.getElementById('checklist_items').style.color = "red";

means that font color will change but checkbox has no text

Upvotes: 0

Related Questions