JPRB JPRB - 1 year ago 94
Javascript Question

How to add independent buttons at the end of each data row in Jquery

So I'm getting data from a back-end through an AJAX GET method, and presenting it in a list(below) in html. I tried to put the button tag in there and I get the buttons on the list but I'm not sure how to use the delegate and others to make it work.

So how can I put independent buttons that send the users to a details page about the cafeteria in that list? (This is just a personal project)


var $cafeterias = $('#cafeterias');
var $Name = $('#CName');
var $Location = $('#CLocation');

function DispCafeteria(cafeteria) {
$cafeterias.append('<li> Name: '+cafeteria.Name+'Location: '+cafeteria.Location+'<button id="Details">Details</button>'+'</li>');

type: 'GET',
url: 'some url',
success: function (cafeterias) {
$.each (cafeterias, function (i, cafeteria){
error: function() {
alert('Error while loading cafeterias');


Answer Source

A few nit pick:

  • Don't name functions with a leading capital letter unless your planning to instantiate it (constructor function). It confuses people since this is the common de facto standard.
  • Avoid nested callback logic. Use a promise interface instead. (jQuery has one).
  • Don't construct interactive DOM elements with HTML strings. It makes it difficult to attach events to it. An exception is using event delegation which in your example is a better more performant way to do that.

You should break your problem space down. Separate concerns into smaller chunks.

Fetch AJAX Data:

function fetchData() {
  return $.ajax({
    type: 'GET',
    url: 'some url'

Handle errors:

function handleErrors(err) {
  alert('Error while loading cafeterias');

Construct the DOM:

function cafeteriaToString(cafeteria) {
  return 'Name: ' + +
    ' Location: ' + cafeteria.location;

function constructDataTable(cafeterias) {
  $.each(cafeterias, function (i, cafeteria) {
    var $button = $('<button/>')
      .data('details-id', i);

Attach a delegated event:

function handleButtonClicks(e) {
  var detailsId = $(this).data('details-id');
  // Do something with detailsId

Putting it all together:

function init() {

  $('ul').on('click', 'li>button', handleButtonClicks);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download