Ad

How To Create HTML Button Based On Database Content?

- 1 answer

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.

Ad

Answer

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);
}
Ad
source: stackoverflow.com
Ad