0

I have an array of Strings in my users.js which I render to my ejs page and then there is an onclick method where it is passed to a js function like below users.js

console.log("count ",count);
res.render("index2", {title: 'some data', imgsrc : variabled, coun : count});

and index2.ejs

<button onclick="popu('<%= coun %>');">

and popu() is

function popu(coun) {
    var select = document.getElementById("selectNumber");

    for(var i = 0; i < coun.length; i++) {
        var opt = coun[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
    }
}

So, basically it is filling a drop-down menu. The problem is that console.log(count) consoles this

count  [
  'Forest', 'Ocean',
  'Port', 'Airport',
]

but the drop-down menu is

F
o
r
e
....

And I am unable to get why is the array iterating over these strings too.

Note: the count array was formed by pushing mongodb query results like this

var count = [];

var arr = await coll.find().toArray();
    for(var i=0; i<arr.length; i++) {
        val = String(arr[i].Name)
        count.push(val);
    }

Any help is appreciated

mr.loop
  • 818
  • 6
  • 20
  • If `coun` is an array, what exactly do you think `'<%= coun %>'` is going to produce? – Phil Jan 13 '22 at 04:34
  • @Phil Nothing, I assume it is passing that array to the function – mr.loop Jan 13 '22 at 04:35
  • 1
    @Phil So basically it was passing a string to the function. That's why whole object was iterated as a string. – mr.loop Jan 13 '22 at 04:39
  • 1
    Yep. I wouldn't recommend injecting objects into HTML attributes, it's bound to have a problem with quote nesting – Phil Jan 13 '22 at 04:45

0 Answers0