I’m trying to make a list of items editable and update with AJAX using jQuery.
HTML
<ul>
<li data-id="1">
<span class="title">Title 1</span><span><a href="#" class="changeLink">Change</a></span>
</li>
<li data-id="2">
<span class="title">Title 2</span><span><a href="#" class="changeLink">Change</a></span>
</li>
<li data-id="3">
<span class="title">Title 3</span><span><a href="#" class="changeLink">Change</a></span>
</li>
</ul>
jQuery
$('a.changeLink').on('click', function(e)
{
e.preventDefault();
// get parent LI element
var li = $(this).closest('li');
// catch current title
var title = li.children('span.title').text();
// replace span
li.children('span.title').html('<input type="text" value="'+title+'" />');
// change the link class and label
$(this).removeClass('changeLink').addClass('saveLink').text('Save');
});
$('a.saveLink').on('click', function(e)
{
e.preventDefault();
// get parent LI element
var li = $(this).closest('li');
// get the id for the AJAX query
var id = li.attr('data-id');
// get the input value
var title = li.children('span.title input').val();
// restore span text with new
li.children('span.title').text(title);
// restore link
$(this).removeClass('saveLink').addClass('changeLink').text('Change');
// make AJAX post to save new title
$.post('updatetitle.php',{ 'id': id, 'title': title }, function(){ alert('OK'); });
});
My problem seem to be that the saveLink click event never occurs. Also the changeLink click event seem to happen more than once. Why does this happen – the link don’t have the changeLink class anymore?
I put this in a jsFiddle here: http://jsfiddle.net/jtheman/SZk4h/1/
Glad if I can get some input, what is my error?
The event will be associated to an element and not specifically to a class..
If you want to work it with class you might need to delegate the event
UPDATED CODE
Your problem was this line
.children()will only get the immediate children of the element.Replace it with
Check Updated Fiddle