Reputation: 204
I'm trying to append a list element with a remove function with it. I already created the remove function and I can appended the element but have no idea how to append the element with the remove function with it.
here's the code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btn1").click(function () {
var listname = $('#listname').val();
$(".container").append($('<ol>', {
text: listname
}));
});
$("#btn2").on('click', function () {
var name = $('#name').val();
$('ol').append($('<li>', {
text: name
}));
});
$('ol').on('click', '.btn3', function () {
$(this).parent('li').remove();
});
});
</script>
<title></title>
</head>
<body>
<ol>
<li>List item 1 <button class="btn3">remove</button></li>
<li>List item 2 <button class="btn3">remove</button></li>
<li>List item 3 <button class="btn3">remove</button></li>
</ol>
<form>
<input id="name" type="text"> <button id="btn2">Append list items</button>
</form>
</body>
</html>
Tips, comments will be much appreciated
Upvotes: 1
Views: 133
Reputation: 36551
create <li>
append <button>
to it.. and then append it to the <ol>
try this
$("#btn2").on('click',function(){
var name = $('#name').val();
var $li=$('<li>', { text: name}); //creating li element.
$li.append($('<button />',{text:"remove","class":"btn3"}).appendTo('ol');
//--^^^^^^^^^---- append created button to lu ---append li to ol
});
Upvotes: 0
Reputation: 388436
Try
$("#btn2").on('click', function () {
var name = $('#name').val();
$('<li>', {
text: name
}).appendTo('ol').append($('<button />', {
'class': 'btn3',
text: 'Remove'
}))
});
If the ol
is added dynamically then
$(document).on('click', 'ol .btn3', function () {
$(this).closest('li').remove();
});
Demo: Fiddle
Upvotes: 1