I’m using a table for a coordinate system, and with a function in each td element to update the field value.
[ ][ ][X][ ]
[ ][X][X][X]
[X][ ][ ][ ]
When I click an empty element, I want it to set the value to “X” in my database, by getting new partial data from my rails app (and sending GET-variables along), and then re-render the table. This works just fine using my rails app, however ONLY once. It seems like the jQuery function .click() only runs once. The function looks as following: (generated via. coffeescript)
$(document).ready(function() {
$(".field").click(function(e) {
$.get("http://localhost/dinners?ap="+$(this).attr('id'), function(data) {
$("#dinner_table").html(data);
});
});
});
This will run just fine, and once I click an element, it will render new data in the table – but only once! If I redefine the .click() function after I swap the HTML in the function, it allows me to click (and update) twice, etc.
I’m pretty sure this is a basic question, but no luck with the searches so far.
Delegate the event. By doing this you need attach the handler only once.
Will become:
bodycan be replaced with any static parent container.