Add and remove <li> with jquery

Javascript coding ..

Moderators: egami, macek, gesf

Post Reply
benoit1980
New php-forum User
New php-forum User
Posts: 23
Joined: Wed Apr 27, 2016 12:18 pm

Wed May 11, 2016 3:13 am

Hello,

I am trying to add and remove <li> with jqeury, the "add" function works but not the remove. When I click on the "remove" button it just disappears, Any idea why please?

Code: Select all

    <h1 id="title">title</h1>
    <ul>
        <li>List 1</li>
        <li>List 2</li>
        <li>List 3</li>
        <li>List 4</li>
        <li>List 5</li>
    </ul>
    <input type="text"></input>
    <button onclick="add()">Add</button>
    <button onclick="remove()">Remove</button>
    <script>
        function add() {
            var count = $('ul').children().length + 1;
            var txt = "List element " + count;
            var newli = $('<li></li>').text(txt);
            $('ul').append(newli);
        }

        function remove() {
            if ($('ul').children().length == 0) {
                return;
            }
            $('li:last').remove('ul');

        }
    </script>


Thank you,

AdoptiveSolution
New php-forum User
New php-forum User
Posts: 163
Joined: Wed Jun 15, 2016 8:35 am

Thu Jul 21, 2016 2:00 am

You're still there?

I think the remove() funtion is reserved. So I used a different name and made some changes :

Code: Select all

<ul id="list">
	<li>List 1</li>
	<li>List 2</li>
	<li>List 3</li>
	<li>List 4</li>
	<li>List 5</li>
</ul>

<button onclick="add()">Add</button>
<button onclick="remoove()">Remove</button>

<script>
function add() {
	var count = $("#list").children().length + 1;
	var txt = "List element " + count;
	var newli = $('<li></li>').text(txt);
	$('#list').append(newli);
}

function remoove() {
	if ($('#list').children().length == 0) {
		alert("empty");
		return;
	}
	$('#list li:last').remove();
}
</script>

Post Reply