JQuery child element triggering parent click event

I am having problems preventing the child of a parent click event from firing in jQuery. I chatted with Google and came across a couple of different solutions, none of which work for me.

I need to make an editable table cell after clicking on it to asynchronously send and editable text via ajax. I am using jQuery to replace the text with an input field, but it cannot be edited or submitted because each click raises the parent event again.

I've tried using:

$("child").click(function(e){  
  e.stopPropagation();
})

      

And also .unbind("click")

for the parent, once it has been clicked it won't need to be repeated, but that seems to unbind the children as well.

I prepared a fiddle to show the problem correctly.

Any help whatsoever would be great! It drives me crazy.

+3


source to share


3 answers


There are a couple of things here.

  • Every time you click on a table cell, you update the form elements. This includes not only clicking on a cell to switch content to the edit control, but also clicking on a text box to focus on it to make text changes.
  • A click for your button will never fire as it is anchored before the control exists in the dom.

My suggestion was that the controls already exist on the page, but the click of the element should be for controlling the transparency of the text box. Also, put the text you want to click in a span or label or div box and click on it in a way that is different from the actual cell.



$("#td-edit").click(function() {
    $("#td-edit").hide();
    $("#dvEdit").show();
});

$("#btn-comment").click(function(e) {
    $("#td-edit").show();
    $("#dvEdit").hide();
});

      

Updated violin

+1


source


The problem is that the element is being .btn-comment

added dynamically, so you need a delegated handler. Try the following:

$(".td-edit").on('click', '.btn-comment', function(e) {
    e.stopPropagation();
});

      



Updated script

Note in the script - you can see that the event is not propagated because it alert()

does not fire when the item is clicked button

.

+3


source


I have updated your fiddle and it seems to work with what I created. Introducing it here also 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/

0


source







All Articles