slakomy
slakomy

Reputation: 323

How to store list of database items in HTML?

I'm working on a project using Django framework. I'm displaying to user table with data. Next to each row there is an "Edit" button. When user clicks this button, in one of cells of the row select box appears with usernames. Currently to feed this HTML select element with options, I store all usernames in data attribute of div element and when user clicks this "Edit" button, I get the list from this data attribute to create options. It seems to me that it isn't the proper solution. Are there any better solutions to store usernames in a page so I can get them when needed? Current code:

<div id="usernames" data-usernames="{{users |safe}}" class="hidden"></div>
(...)

var divWithUsernames = document.getElementById("usernames");
var usernames = (divWithUsernames.getAttribute("data-usernames").replace(/&(l|g|quo)t;/g, function (a, b) {
    return {
        l: '<',
        g: '>',
        quo: '"'
    }[b];
}));
for (var i = 0; i < usernames.length; i++) {
    var val = usernames[i];
    var option = $("<option />", {value: val, text: val});
    option.appendTo($select);
}

Upvotes: 1

Views: 1699

Answers (1)

Control Freak
Control Freak

Reputation: 13213

I would use ajax to load the json data and populate the select list any time I need.

It would look something like this:

JSON "users.json"

[{ user: "bob", age: 40 }]

jQuery:

$.get("users.json",function(data){
  $.each(data,function(i,v){
     $("<option/>").html(v.user).val(v.age).appendTo("select#usernames");
  });
});

Upvotes: 2

Related Questions