tags:

views:

82

answers:

3

On inserting the new <li>, I have to set the value of the button clicked to Delete. How can I do that?

With the actual code, it`s working only once, and on adding other list, the button no more has the the value 'Delete'.

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

    if (text == "Delete") { 
        $(this).parent().remove(); 
    } else { 
        $(this).val("Delete"); 
    }
});

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

<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>
+3  A: 

Use text() instead of val()

var text = $(this).text();
if (text === "Delete") 
{
    $(this).parent().remove();
}
else
{
    $(this).text("Delete");
}
rahul
A: 

Yeah. These are often misused:

.val() get/set the value of an input

.text() get/set the text of an element (e.g 'text' in the following <td>text</td>(

.html() add HTML inside an element, e.g. <a>anchor</a> in the following <td><a>anchor</a></td>

James Wiseman
`.html()` does not "add", it "sets".
Alex Bagnolini
+1  A: 

I think your id selector is wrong

It should be

$("#mylist li:last-child button")

instead of

$("#categorylist li:last-child button")

and change

$(this).parent().append('...);

to

$(this).parent().parent().append('...');
rahul
If you find yourself using parent().parent() its time to switch to closest().
PetersenDidIt