Skip to content Skip to sidebar Skip to footer

When Clicked Insert Text Into Ul Li

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 c

Solution 1:

You need a different kind of selector.

$(document).ready(function () {
    i = 0;
    $("#test").click(function () {
        var t = $('#text').val();
        varUL = document.createElement('ul');
        varLI = document.createElement('li');
        $(UL).attr('id', 'main-list' + i).appendTo('body');
        $(LI).text(t).appendTo("#main-list"+i);
        i++;
    });
    $(document).on('click', "ul li", function () {
        $(this).remove();
    });
});

It is known as delegated event. I didn't know the exact name.

Working fiddle link.

EDIT

The id must be unique.

Solution 2:

Just a small change is enough:

$("body").on("ul#main-list li", 'click', function(){
    $(this).remove()
});

Solution 3:

As Dream Eater mentioned you need to Add the click event using on unless you are going to add a click handler each time you add an LI.

To accomplish the rest of your question you need to do a few things.

You can't just blindly remove the list items if you are going to also remove the list when it is empty. To do this you need to be checking to see how many items remain in the list each time you click an item. If there is only one, then you need to remove the list as well as the item in the click.

Furthermore if you are going to create a new list each time you click the test button you have the right script, but it sounds like you desire to have a single list. To accomplish this you need to check if the list exists before you create it.

Finally I modified your code to take syntactical advantage of jQuery methods and I came up with this:

$(document).ready(function(){
    $("#test").click(function(){
        var t = $('#text').val();
        varLI = $('<li/>');

        if($('#main-list').length == 0){
            varUL = $('<ul/>');
            UL.attr('id','main-list');
            $('body').append(UL)
        }
        LI.text(t).appendTo('#main-list');
        LI.appendTo("#main-list").text(t);
    });
    $(document).on('click', "#main-list li", function(){
        if($('#main-list').children('li').length ==1)
        {
            $(this).remove();
            $('#main-list').remove();
        }else{
            $(this).remove();
        }
    });
});

This example demonstrates how it works. By checking first to see if the list exists each time you click the button, you only get one list. By checking if there is only one LI in the list when clicking an item, you can easily capture the 'remove last item' click.

The last thing I would suggest here is to add some error trapping for when the value of the text box is empty.

Post a Comment for "When Clicked Insert Text Into Ul Li"