I am trying to make my code so that when I click on a added list item, it changes the color red, as well as add a slash through it. The full code for the program is below
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ultimate List Maker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
* {margin:0; padding:10px; text-align:center;}
body {width:80%; margin:40px auto; min-width: 400px; max-width: 600px}
header {background:red}
#counters {background:lightgreen;font-weight: bold; font-size: 150%;display: flex; justify-content: space-around; flex-wrap: wrap}
button {background: #ff9999; width: 100px; }
main {background:yellow; min-height: 80px}
footer {background:lightblue}
button:hover {background: pink}
li {list-style: none; font-weight: bold; font-size: 150%}
.complete {color: red; text-decoration: line-through}
</style>
</head>
<body>
<main>
<ul id="list">
<li></li>
</ul>
<button id="showForm">Add New Item</button>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Add description">
<input type="submit" id="add" value="add">
</form>
</main>
<footer><h2>Making lists since 2018</h2></footer>
<script>
$(document).ready(function(){
$('#showForm').click(function(){
var li = $('#itemDescription').val();
$('#list').append('<li>'+li+'</li>');
});
});
</script>
</body>
</html>
Ive tried this line of code, but it does not do anything when the item is clicked
$(document).ready(function(){
$("li").click( function() {
$("li").css("color", "#d49a9a");
$(this).css("color", "#c2c0c0");
});
});
2
Answers
First you have to ensure prevent submitting form to not reload page.
Append this
"<li class='li'>" + $("#itemDescription").val() + "</li>"
Whenever you click a list only that list element will be changed
I hope you have got your solution
I’m assuming that when the
<input type="submit">
button is pushed everything disappears so you have another button added unnecessarily. Whenever a<input type="submit">
or<button></button>
that’s inside a<form>
is clicked, a "submit" event is triggered. So instead of using a "click" event on a<button>
outside of<form>
use the "submit" event triggered on the<form>
. The default behavior when a<form>
is submitted is to send it’s data to a server and leave a blank page if there’s no response from the server. In order to avoid a blank page useevent.preventDefault()
.The next problem is resolved by toggling the
".complete"
class on any<li>
the user clicks.Example