Reputation:
I am trying to do a school project. I have to make a list and after the checkbox is clicked supposed to be crossed off. I don't know Javascript yet and I'm still trying to figure it out. I am wondering why this isn't working.
function crossout(id) {
var box = document.getElementById(id);
box.style = "text-decoration: line-through";
}
<body>
<h1>Hello World!</h1>
<h3>Shopping List</h3>
<p id="box1">
<input type="checkbox" onclick="crossout"("box1") />
Banana
</p>
<p id="box2">
<input type="checkbox" onclick="crossout"("box2") />
Noodles
</p>
<p id="box3">
<input type="checkbox" onclick="crossout"("box3") />
Eggs
</p>
<script src="app.js" charset="utf-8"></script>
</body>
Upvotes: 0
Views: 2142
Reputation: 41913
Instead of binding events strictly inside the DOM, I would suggest you to catch every checkbox
element, then iterate over it using Array#forEach
and bind an eventListener
to each of them. If you will check the checkbox
, checked
class will be applied to it's parent - p
element.
It looks fine and works even better.
var elems = document.getElementsByClassName('box');
Array.from(elems).forEach(v => v.addEventListener('change', function(){
this.parentNode.classList.toggle('checked');
}));
.checked {
text-decoration: line-through;
}
<h1>Hello World!</h1>
<h3>Shopping List</h3>
<p id="box1">
<input type="checkbox" class='box'>Banana
</p>
<p id="box2">
<input type="checkbox" class='box'>Noodles
</p>
<p id="box3">
<input type="checkbox" class='box'>Eggs
</p>
Upvotes: 1
Reputation: 12815
You have a typo in your checkboxes:
onclick="crossout"("box1")
This should be:
onclick="crossout('box1')"
Your original way set onclick
only to "crossout"
.
Upvotes: 1