views:

185

answers:

2

I have the following code. On cliking the button on the last li, I can create the new li. However, once created, if I click on the latest button created, new li is created. It seems it doesn`t recognise the last created li as the last li. Can someone help on this please.

<html xmlns="http://www.w3.org/1999/xhtml" >

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
        <script type="text/javascript">
            $(document).ready(function() {
                $("#mylist :button").click(function() {
                    var text = $(this).val();
                    if (text == "Save") {
                    }
                });

                $("#mylist li:last-child").click(function() {
                $(this).parent().append('<li>' + '<input type = "textbox">' + '<input type = "button" value= "Save">' + '</li>');

                });

            });

        </script>

<div>
<ul id="mylist">
<li id="1">1<button id="Button3">Delete</button> </li>    
<li id="2">2<button id="Button2">Delete</button></li>
<li id="3">3<button id="another_entry">Save</button></li> 
</ul>

<ul id="mylist2">
<li> test1 <button id="Button6">Delete</button></li>
<li> test2<button id="Button5">Delete</button> </li>
<li id="6"><button id="Button1">Delete</button></li> 
</ul>


</div>
A: 

Instead of:

 $(this).parent().append('<li>'.........

Try

 $("#mylist").append('<li>'.........
Sarfraz
this won't help, as OP stated, first click is functional, however second is not... so there is no problem in referencing `parent` element
Juraj Blahunka
+2  A: 

You need to use live instead of bind as bind iterates elements only once, however live creates a listener, which attaches events dynamically, even to newly created elements.

You code should conform to this sample:

$("#mylist li:last-child")
    .live('click', function() {
        // append element
    });

tested with jQuery 1.4.0

Juraj Blahunka