I got a problem with my jQuery code, when I press the ‘edit’ button, and then the ‘cancel’ button, if I then press ‘edit’ again, it won’t work.
HTML
<div id="2">
<button class="edit" id="2">edit</button>
</div>
jQuery
$('.edit').click(function(){
var id = $(this).attr('id');
var post = $('div#'+id);
var title = $('div#'+id+'>h1').html();
var content = $('div#'+id+'>p').html();
var edit = '<input type="text" class="title" id="'+id+'" value="title"><br>';
var edit2 = '<textarea class="content" id="'+id+'" rows="10" cols="100">content</textarea>';
$(this).remove();
post.append(edit);
post.append(edit2);
post.append('<br><button id="'+id+'" class="save">save</button><button id="'+id+'" class="cancel">cancel</button>');
$('.cancel').click(function(){
$('div#'+id+'>input').empty().remove();
$('div#'+id+'>textarea').empty().remove();
$(this).empty().remove();
$('.save').empty().remove();
$('div#'+id+'>br').remove();
post.append('<button class="edit" id="'+id+'">Edit</button>');
});
/*$('.save').click(function(){
var newTitle = $('input#'+id+'.title').val();
var newContent = $('textarea#'+id+'.content').val();
console.log(newTitle);
console.log(newContent);
console.log(id);
$.post('/editPost', {id: id, title: newTitle, content: newContent}, function(){
location.reload();
});
});*/
});
jsfidde: http://jsfiddle.net/pHCT8/2/
Firstly you CANNOT use same ID on two elements, this will surely render browser and JS errors.
(Also if youre not using HTML5 DOCTYPE then you shouldn’t have ID’s starting with a number)
Then use jQuery
on()syntax as a live handler:Note that the starting
$('#2')is the outer limit of where you want the click listener to work. If you need it wide then use$('body').on('click','.edit', function(){this will listen to all.editclicks inside the whole body tagReason is that your click event handler only work upon elements loaded with the DOM, but your ajax edit function will create elements that wasn’t in the DOM when loaded (dynamically created).