February 22, 2013
When clicked insert text into ul li
Question by user1847112
I’m new to javascript/jquery and could need some help. When I click on the test button a new ul
containing an li
is appended into the body with the value of the input field. When clicked on the li
element it should be removed. If there is nothing inside the ul
, it should be also removed.
How can I make the code to create unordered list once and then insert li
‘s inside? Also, how should I proceed to remove a li
when I click on them?
This is the code I have now:
<input type="text" value="" id="text" />
<input type="button" id="test" value="Test" />
$(document).ready(function(){
$("#test").click(function(){
var t = document.getElementById("text").value;
var UL = document.createElement('ul')
var LI = document.createElement('li')
$(UL).attr('id','main-list').appendTo(body)
$(LI).appendTo("#main-list").text(t)
});
$("ul#main-list li").click(function(){
$(this).remove()
});
});
Answer by Starx
Just a small change is enough:
$("body").on("ul#main-list li", 'click', function(){
$(this).remove()
});