I have a ton of code but I'll only show the part that I'm currently stuck on. What I'm trying to fix is when I append data to my table, and change the event, the previous data also gets appended to the new data in my table. I understand that there is a lot of articles on SO about this and I looked them up where some have suggested using detach()
. But I don't want to append the data later on so that doesn't apply to me. I also tried to use remove()
and it works but on event change, it removes the data immediately before the data initially gets loaded in.
I have no console errors and everything is wrapped in document.ready()
function
What I want to achieve:
On event change, Load data if user changes input, delete previous data from previous event and load in the new data from the current event.
Here is my code:
var renameLocations; switch(picker.chosenLabel){ case "Example event1": renameLocations = []; dataLabel = <?php echo json_encode($locations) ?>; dataCount = <?php echo json_encode($count) ?>; var locationsPHP = <?php echo json_encode($locations) ?>; var countPHP = <?php echo json_encode($count) ?>; locationsPHP.forEach(function(item, i){ //$('table#relevantdataModal').find('tbody').innerHTML = ''; // This works but it deletes the data immediately on event change Rather than loading in data and deleting it later... $('table#relevantdataModal').find('tbody').remove(); $('table#relevantdataModal').find('tbody').append('<tr><td>' + locationsPHP[i] + '</td><td>' + countPHP[i] + '</td></tr>'); }); break; case "Example event2": renameLocations = []; dataLabel = <?php echo json_encode($todaylocations) ?>; dataCount = <?php echo json_encode($todaycount) ?>; break; } // End switch statement
Rather than remove( ) and append () you may want to try innerHTML for vanilla JavaScript. In jQuery this is also done with a .html().
In your case it would be: $('table#relevantdataModal').find('tbody').html(...add your stuff...)
Here are some quick W3 references for the vanilla JS and jQuery.
Vanilla JS - W3 https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_innerhtml
jQuery - W3 https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_set
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.