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()
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!