I'm trying to make a system where a user can add or delete a row into a temporary table so that they can edit a JSON "table" that'll be sent via AJAX to get some query results (haven't figured that bit out yet). I 'push' each inputted row to add it as a new array, refresh the table to include it, and then delete entries by 'splicing' the array with matching ID and refresh the table again. So far, it looks a little like this:
let jsonString = '{"arrays":[]}';
$(".add-row").on("click", function(){
let obj=JSON.parse(jsonString);
obj['arrays'].push({"ID":var0,"field1":input1);
jsonString = JSON.stringify(obj);
let text = "";
for (let i in obj.arrays) {
text += ""+ obj.arrays[i].field1 +" }
document.getElementById("table1").innerHTML = text;
$(".delete-row").on("click", function (){
let thisID = $(this).attr('value');
let obj = JSON.parse(jsonString);
let index = obj['arrays'].findIndex(function(item, i){
return item.ID === thisID
});
obj['arrays'].splice(index,1);
jsonString = JSON.stringify(obj);
let text = "";
text += ""+ obj.arrays[i].field1 +" " }
document.getElementById("table1").innerHTML = text;
});
});
My issue is that this seems to mostly work, except that while you can add multiple rows, you can only ever delete one row, unless you add any more again. I'm sure the way I've handled it is generally less than ideal as this is my first ever attempt with JSON and I only mess around as a hobby. I'm sure it must have something to do with the fact that the delete-row is nested inside the add-row, but it doesn't work at all if they're siblings. Do I need to run it as some sort of event listener instead? Do you think it can even work at all in this format? Are you horrified and recommend I do this any other way? I've looked into .append, but I can't see how I would make it work with the JSON.
(I'm also not sure why it only works if some parts are formatted per JQuery and others per regular JS; if I try swapping any parts between the two it throws a fit).