简体   繁体   中英

How to delete an array item in EJS from an Onclick of button?

I am creating a to-do list and need help with adding a button in EJS that can delete an object from an array itemArr . I am displaying my <li> items via a for loop, which are objects in the array. Each object has a name, start time, end time and an id.

itemArr.push({name:newItem, st:starttime, et:endtime, id:id});

Is there a way to create an onclick button that can delete an object from the array and hence remove it from the "To do" listing? I can easily remove it in html, but when i add a new item, the array is refreshed and the listing will reappear, so i must remove it from the array.

这是它的样子

Currently, this is my EJS Code , where the List is generated from a for loop, and res.render shows where the itemArr is binded to ITEMARRAY.

<body>

    <h2 style="text-decoration: underline;"> To do:</h2>
    <ol type="1">
        <% for (var i=0;i<ITEMARRAY.length;i++){ %>
            <li> <%= ITEMARRAY[i].name %> | <%= ITEMARRAY[i].st %> - <%= ITEMARRAY[i].et %> <input type="checkbox"> <button onclick="myFunction(i)" id="remove">X</button> </li> 
        <% } %>

    </ol>

<script>
    function myFunction() {
      var x = document.getElementById("remove").parentNode.remove();
    }
</script>

Here is the app.js :

app.get("/", function (req, res) {

  res.render("list", {ITEMARRAY: itemArr}); //pass an object into list.ejs with keyval pair


});

app.post("/", function(req,res){
    var newItem = req.body.newItem;
    var starttime = req.body.startTime;
    var endtime = req.body.endTime;
    var id = 0;

    //checking validity of range
    var start = parseInt(starttime.split(":"));
    var end = parseInt(endtime.split(":"));

    var difference = (end - start) / (86400000 * 7);
    if (difference < 0) {
        // throw new Error("The start time must come before the end time.");
        res.render("fail");
    }
    else
      itemArr.push({name:newItem, st:starttime, et:endtime, id:id}); //if all ok, then push to arr
      sortList(itemArr); 
      res.redirect("/");


})

TL; DR; EJS is a server-side rendering solution so you cannot do that.

Because EJS is an SSR solution all the rendering happens on the server and then the client receives an HTML page. From now the page lives in the Browser, and to change it you need to use some browser JS code to do that.

the answer is to use mongodb, then make a post request via the button.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM