Reputation: 5212
OK, I'm just getting to grips with jQuery and have a little issue.
I have a link that will change the contents of a <div>
with a textarea
<a href="#" class="edit">Edit</a>
On click I want the save link to change the contents of the textarea in the original <div>
heres the code I have for this
$(function(){
var content = $('.edit').text();
$('.edit').click(function(){
$('.content').html('<textarea class="text">' + content + '</textarea>');
$('.text').focus();
$(this).removeClass('edit').addClass('save').text('Save');
}
$('.save').live('click', function(){
$('.content').html($('.text').val());
$(this).removeClass('save').addClass('edit').text('Edit');
// Ajax code to save new content
});
});
My problem is when I click the Edit button because I add the class save
it also executes the .save
click function. How can make sure the .save function is only executed when I click the save function.
Upvotes: 1
Views: 963
Reputation: 253328
Attach your click event-handler to the a
element itself, then check whether or not it has the class of 'edit' or 'save', and perform actions based on that eventuality:
$('a').click(
function(){
if ($(this).hasClass('edit')){
$(this).removeClass('edit').addClass('save').text('save');
}
else if ($(this).hasClass('save')){
$(this).removeClass('save').addClass('edit').text('edit');
}
return false; // or not, you decide...
});
Upvotes: 2
Reputation: 66388
Instead of messing around with the classes I would check the text instead - as you already have it hard coded it won't make much difference:
$('.edit').live('click', function() {
var curText = $(this).text();
if (curText === 'Edit') {
$('.content').html('<textarea class="text">' + content + '</textarea>');
$('.text').focus();
$(this).removeClass('edit').addClass('save').text('Save');
} else {
$('.content').html($('.text').val());
$(this).removeClass('save').addClass('edit').text('Edit');
// Ajax code to save new content
}
});
Upvotes: 0
Reputation: 2202
I think you need to tell jquery that you will handle the click event, e.g.
$('.edit').click(function(event){
event.preventDefault();
$('.content').html('<textarea class="text">' + content + '</textarea>');
$('.text').focus();
$(this).removeClass('edit').addClass('save').text('Save');
}
Which will hopefully stop the click event and only make the save trigger when clicked.
Upvotes: 0