Reputation: 247
I'm having issues preventing a child element from activating a parent click event in jQuery. I've Google'd around and have stumbled upon a couple different solutions, none of which appear to work for me.
I need to make a table cell editable after clicking it so that I can submit the edited text asynchronously via ajax. I'm using jQuery to replace the text with an input field but it then can't be edited or submitted because each click fires the parent event again.
I've tried using:
$("child").click(function(e){
e.stopPropagation();
})
And also .unbind("click")
on the parent as once it's been clicked it won't need to be clicked again but this seems to unbind the child too.
I've prepared a fiddle in order to properly show the problem.
Any help at all would be super! It's driving me crazy.
Upvotes: 3
Views: 1748
Reputation: 37819
A couple things here.
My suggestion would be to have the controls already exist on the page, but have the clicking of the element be for controlling the VISIBLITY of the textbox. Additionally, put the text to be clicked into a span or label or div, and click on it that way, as opposed to the actual cell.
$("#td-edit").click(function() {
$("#td-edit").hide();
$("#dvEdit").show();
});
$("#btn-comment").click(function(e) {
$("#td-edit").show();
$("#dvEdit").hide();
});
Upvotes: 1
Reputation: 4331
I've updated your fiddle and it seems to work with what I created. Putting it here as well for reference:
function clickEdit() {
$(this).html("<div class=\"input-append\"><input class=\"updater-text span2\" type=\"text\" value=\"" + $(this).text() + "\" /><button class=\"btn-comment\" type=\"button\" id=\"appendedInputButton\">Save</button>").off('click');
$('#appendedInputButton').on('click', function(e) {
e.stopPropagation();
e = $(this);
console.log(e.prev().val());
e.parent().html(e.prev().val()).on('click', clickEdit);
});
}
$(".td-edit").on('click', clickEdit);
Fiddle link: http://jsfiddle.net/9F67j/14/
Upvotes: 0
Reputation: 337560
The problem is because the .btn-comment
element is being dynamically appended, so you need a delegated handler. Try this:
$(".td-edit").on('click', '.btn-comment', function(e) {
e.stopPropagation();
});
Note in the fiddle - you can see the event is not being propagated because the alert()
does not fire when clicking the button
element.
Upvotes: 3