tags:

views:

60

answers:

2

I have various. How do I add a new list based on the button clicked in that particular ul How to get the ul of the button saved clicked and create and add li to that ul?

<ul id ="list1"><li>item1</li><input type= "Button" id = "test1" value = "Save"></ul>
<ul id ="list2"><li>item11</li><input type= "Button" id = "test11" value = "Save"></ul>

the Jquery code is as follows:

   $(document).ready(function(){ 

     $("#list :button").click(function(){ 
         var text = $(this).val();

        if ( text == "Delete") {
           $(this).parent().remove(); 
        }
               if(text =="Save")
               {
                   //How to get the UL of the button saved clicked and create and add li to that UL
               }
   }); 
});​
+1  A: 
$(this).closest('ul').append('<li>');

But you shouldn't have a button directly in the UL. UL should only contain list items.

Max Shawabkeh
`.append('<li/>')` would be more correct/valid!
Andreas Niedermair
If you're doing XHTML (if `<li>` allows self-closing; not all tags do). In HTML, `<li>` is valid, while `<li/>` isn't.
Max Shawabkeh
A: 

The first problem with your code is that your selector is wrong. To select the button inside the ul you can use

$("ul :button")

and you can write code like this.

I assume your requirement is

On the click of button, add a new li item to the list on button click and change the value of button from Save to Delete

On click of button again, delete the newly created li from the ul and change the value of button from Delete to Save.

For this you can use the toggle function

$("ul :button").toggle(
    function(){
        var elem = $(this);
        elem.closest("ul").prepend("<li>item</li>");
        elem.val('Delete');
    },
    function(){
        var elem = $(this);
        elem.closest("ul").find("li:first-child").remove();
        elem.val('Save');
 });

If you want to delete the ul element on second click you can replace

elem.closest("ul").find("li:first-child").remove();

with

elem.closest("ul").remove();
rahul