1

Trying to learn handling database information and my mission has been to dynamically create buttons based on content from a database query.

My Javascript is as follows:

var Datastrore = require("nedb");
var db = new Datastrore({ filename: "macros.db" });
db.loadDatabase(function(err) {
  db.find({}, function(err, docs) {
    console.log(docs); //all docs
  });
});

This puts out in console my db info:

0: {name: "asas", command: "asas", _id: "6L83tJLl7ks0iS0b"}
1: {name: "asas", command: "asas", _id: "9kXMI7DdJBWK0L1W"}
2: {name: "qw", command: "qw", _id: "UmOaMJxYjMNjcEQ0"}

Now I can't figure out how I can use this info to dynamically create buttons on my html page.

j1rjacob
  • 411
  • 11
  • 27
Christophermp
  • 176
  • 1
  • 3
  • 13

2 Answers2

0
for (var doc in docs) {
      var element = document.createElement("button");
      //Assign different attributes to the element. 
      element.setAttribute("name", doc.name);
      element.innerHTML = doc.name
      element.setAttribute("id", doc._id);           
      //element.setAttribute("onclick", ); If you wish to add click event

      //Append the element in page (in span).  
      document.body.appendChild(element);
}
0

First is you need to loop in each of the entries:

for(var data in docs){

    var btn = document.createElement('button') //creates a new button element
    var t = document.createTextNode(data.name) //assuming button's name = 'name'

    btn.appendChild(t)
    btn.id = data._id
    btn.onclick =  data.command //assuming 'command' is a defined function

    document.body.appendChild(btn)
}
Shan Surat
  • 304
  • 4
  • 13