Reputation: 1436
I just started to learn JavaScript/jQuery, and I made a little test website to practice coding.
In one of the tests I made, there is a list that says Milk and Eggs. There is an input field and a button, which you can type something, click the button, and add it to the list. I then added an option where if you click on one of the list items, it removes it. This works, but only on the preset Milk and Eggs items, not any items that you add yourself.
I think it's because the code wasn't loaded for the newly added items, but I'm not sure. Can someone help?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Practice 3</title>
<link href="index.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<div class="Title" align="center">
<h1>Hello</h1>
<p>This website will use JavaScript to create interactive elements.</p>
</div>
<div class="1">
<h3>Test 1</h3>
<ul id="list">
<li>Milk</li>
<li>Eggs</li>
</ul>
<input id="textbox">
<button id="add">Add to list</button>
</div>
<script>
$('#add').click(function() {
var listvalue = $('#textbox').val();
$("#textbox").val("");
$('ul').append('<li>' + listvalue + '</li>');
});
$('#textbox').keypress(function(event) {
if(event.which === 13) {
var listvalue = $('#textbox').val();
$('#textbox').val("");
$('ul').append('<li>' + listvalue + '</li>');
}
});
$('li').click(function(e) {
$(e.target).remove();
});
</script>
</body>
</html>
Upvotes: 1
Views: 7534
Reputation: 413
Answered by Gone Coding on stackoverflow:
https://stackoverflow.com/a/34857252/7074256
And here is example how to do it with jquery:
function moveItems(origin, dest) {
$(origin).closest("li").appendTo(dest);
}
$(document).on('click', '.add', function () {
moveItems(this, '#listTwo');
});
$(document).on('click', '.remove', function () {
moveItems(this, '#listOne');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/r7j3odyy/4/
Upvotes: 0
Reputation: 43852
You can use on
to bind the click even to the document, then specify a selector to specify that it should only trigger for li
elements:
$(document).on('click', 'li', function (e) {
$(this).remove();
});
This will still work with newly-added li
elements because the event-handler itself is bound to the document itself, not the individual elements. It simply performs a runtime check to ensure that the dispatched event matches the provided selector.
Upvotes: 3
Reputation: 77482
Use event delegation
$('#list').on('click', 'li', function(e) {
$(this).remove();
});
Upvotes: 4