JQuery event listener when text was changed in cell <td>?
4 answers
To extend the mway answer , here is some code.
var td = $('#my-table tr td:eq(1)'); var tdHtml = td.html(); setInterval(function() { if (td.html() !== tdHtml) { // it has changed tdHtml = td.html(); } }, 500); ... and for his second sentence.
function updateTd(html) { $('#my-table tr td:eq(1)').html(html); // additional code } You can also bind the DOMSubtreeModified event to an element, but browser support is not the best.
+6
Not initially, no. You have several options:
1) Use setInterval() to check the value against its previous value and act accordingly if it is different.
2) Use the general method of changing the contents of cells, so that you can also perform additional logic when its value changes without overwriting it several times.
+4
Horrors. May be acceptable in 2010.
const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { // NB the 1st char put or typed into a TD causes a mutation in the TD... // but chars 2 ... n cause a mutation in its child '#text' node let target = mutation.target; if( target.cellIndex === undefined ){ target = target.parentElement; } // NB don't use a "truthy" test for cellIndex here: you would miss index 0! if( target !== null && target.cellIndex !== undefined ){ // ... then the target is the TD where the content has changed. } }); }); const config = { attributes: true, childList: true, characterData : true, subtree : true }; observer.observe( htmlTable, config ); 0