Background: There are some values on my website which shall be editable via JavaScript and Ajax. The Ajax is working fine and I can edit values but after I saved the value I cannot edit it again without reloading the page.
I reduced the problem to this: The original element gets replaced with a HTML form. When the form is submitted the form itself is replaced by the new version of the display element, but the event listener is broken.
I put together some sample JS code (JSfiddle) which doesn’t work as I expect.
var text = $('<em/>').text('click me!');
text.click(function() {
var button = $('<input type="button" value="Click me, too" />');
button.click(function() {
$('#container').html(text);
});
$('#container').html(button);
})
$('#container').html(text);
What shall happen:
- current value displayed
- after text
clicked text replaced with form (text element saved for simplicity) - after button
clicktext displayed again clickon text works again as in step 2 (doesn’t work now)
Why is the click event lost when using the text object again?
The
.html()method (re)sets theinnerHTMLproperty to a text value. These strings have no event listeners – I think that’s a bug in jQuery that.html()accepts anything than strings (and functions); in here your jQuery object seems to be even stringified.To change the content to already existing DOM nodes, you will need to
.empty()the container (or.remove()the text element) and.append()the button element.