1

I am making a todo list so I am adding new input tags with checkboxes on them so I can check off a to do list item. I am having trouble modifying the css so that the text displays a line through it when it is checked. The check function works and it runs but I am unable to put a line through the specific html element.

var add = function() { 
var task = $("#taskTextBox").val(); // references the value inside #task
if(task != ""){
    inc++;
    var itemName = "item" + inc;

    var newObj = $("#list").append("<input id="+itemName+" type=checkbox class="+itemName+">"+task+"<br></br>");// makes a new <p> element
    $("#taskTextBox").val(""); // empties out #task
    var newHeight = $("#list").height() + 40;
    $("#list").css({"height": newHeight});
    addAttributes();


$("input[class=" + itemName + "]").change(function () {
    if ($(this).prop("checked")) {

    $("input[class=" + itemName + "]").css({'text-decoration': 'line-through'});

    } else{
        $("#list").css({"text-decoration":  "none"});
    }
}); 
}};

1 Answer 1

4

EDIT:

I forgot to mention that your code is not working because you are adding your class to the input which is just affecting the checkbox style not the text following it.

For my code to work you just need to modify this line, adding a span to wrap your task. You do not need the change function anymore.

var newObj = $("#list").append("<input id="+itemName+" type=checkbox class="+itemName+"><span>"+task+"</span><br></br>");// makes a new <p> element

SOLUTION:

You can achieve this with plain CSS using :checked pseudo-class and using a span or any other tag that can be used as a selector directly following your input:


JSFiddle


CODE SNIPPET:

.example:checked + span {
  text-decoration: line-through;
}
<input class="example" type="checkbox"><span>Eggs</span>
<input class="example" type="checkbox"><span>Milk</span>

Sign up to request clarification or add additional context in comments.

3 Comments

Good solution, Ricardo, and well presented. +1
Thanks man, can't wait for those level 4 selectors to achieve more things like this. css4.rocks/selectors-level-4
This worked months ago when I checked. I saw I didn't say anything, so thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.