Pug: Call function in each loop using pug/jade

959 Views Asked by At

I'm trying to coding a simple app, like a TO-DO LIST, I need to create dynamically (with incremental id in the divs) when I pressed a Button, and input some text to HTML input. e.x:

<div id="item1">
<div id="item2">
<div id="item3">
<div id="item4">

The problem is that when I tried to get var data it gets me nothing.

How to iterate var data in the each loop? How to call it?

I need your help with the following code:

script.
    var data = new Array(); // creating array

    function add_element(){
    data.push(document.getElementById("t1").value);
    document.getElementById("t1").value=''; //it set blank in box again
    console.log(data)}


div
input(type="text" id="t1")
button(id="" onclick="add_element()") add

ul
    each val, index in {data} //<- how to iterate data var here? how to call it?
        li= index + ': ' + val

Thanks a lot in advance.

1

There are 1 best solutions below

0
On

each loops are meant to iterate over Pug variables (passed to it via Express or other means.) They receive data from the server, but they don't receive data from the client. JavaScript variables cannot be iterated over with Pug's loops; the array you are trying to iterate would thusly need to be created on the server, or you would need to use a regular JavaScript loop to iterate over that array and generate the HTML.