Jump to content

jquery append to inside end of <ul>


seventheyejosh

Recommended Posts

Say I have this UL:

 


<ul id="mylist">
     <li id="1">1</li>
     <li id="2">2</li>
</ul>

 

I want to have a button:

 


<button id="another_entry">Add Another</button>

 

that when clicked will add a new element to the end of the <ul>, but not outside of it, inside it.

 

append() does something like this:

 


<ul id="mylist">
     <li id="1">1</li>
     <li id="2">2</li>
</ul>
     <li id="3">3</li>


 

whereas I need it to do this:

 


<ul id="mylist">
     <li id="1">1</li>
     <li id="2">2</li>
     <li id="3">3</li>
</ul>

 

I'd prefer if it was able to autoincrement the id number, but i'd be happy enough if someone can give me a point towards how to do the append.

 

Thank you very much,

 

Josh.

Link to comment
https://forums.phpfreaks.com/topic/181139-jquery-append-to-inside-end-of/
Share on other sites

append() will do

<ul id="mylist">
     <li id="1">1</li>
     <li id="2">2</li>
     <li id="3">3</li>
</ul>

 

 

after() will do

<ul id="mylist">
     <li id="1">1</li>
     <li id="2">2</li>
</ul>
     <li id="3">3</li>

 

I quickly wrote the following, Is this the kind of thing you are after?

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
    
    <head>
  
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />


        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

	<script type="text/javascript">

	$(document).ready(function() {

		$('#another_entry').click(function() {

			var cur_no = parseInt($('#mylist li:last').attr('id')) + 1;

			$('#mylist').append('<li id="'+ cur_no +'">'+ cur_no +'</li>');

		})

	});

	</script>
        
    </head>

    <body>

	<ul id="mylist">
		<li id="1">1</li>
		<li id="2">2</li>
	</ul>

	<a href="#" id="another_entry">Add Another</a>

</body>

</html>

 

Online Demo

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.