I’m trying to make an editable table for a tournament using jQuery and ajax.
The present table structure is as follows:
<table>
<tr id="result-243">
<td class="name">Somebody</td>
<td class="score_1">9.0</td>
<td class="score_2">7.0</td>
<td class="score_3">7.8</td>
<td class="score_4">9.9</td>
<td class="score_5">7.9</td>
<td class="edit-243"><div id="edit-243" class="edit">Edit</div></td>
</tr>
</table>
What I want is to insert a form when the ‘Edit’ link is clicked. This form would be populated with values from the current entry. I can make this work as follows:
$('.edit').click(function() {
result_id = $(this).attr('id').match(/[0-9]+/);
sel = '#result-' + result_id;
$.get(
myScript.ajax_url,
{
action:'getResults',
id:result_id,
nonce: myScript.nonce
},
function( response )
{
form = "<form id='save-" + result_id"' class='post-me'>";
for(value in response) {
form += "<input type='text' name = '" + value + "' value = '" + response[value] + "' />";
}
form += "<input type='submit' id='save-this' name='save' value='Save' /></form>";
$(sel).html(form);
}
);
});;
I would obviously expect to be able to bind the form to a $.post() request, and that should post the data. However, the problem I seem to be running into is as follows:
If I want to restore the previous table elements (as above) with new values, I can’t click ‘Edit’ again. I think it’s because jQuery will bind events to DOM elements inserted on the fly, but only once. I can’t remove the elements without losing the event binding.
Any ideas for what’s wrong with my design approach?
Can you use ContentEditable instead (html5)? Then you can just wrap up the edited table and send the new values in once they are changed.
http://jsfiddle.net/5Ut8x/
Testing for ContentEditable support.
Thinking about your question some more and your existing framework – I think you can work around the event binding problem by either using
onor not destroying old values until the form is actually submitted. Just hide the table row and replace with a form.Then if the form is actually submitted destroy the old row. If user cancels out of submission then destroy the form and reshow the old row. Here is an example fiddle.
http://jsfiddle.net/5Ut8x/1/