2

I am using Jquery-Bootgrid. http://www.jquery-bootgrid.com/

I need a situation where user can select a Row, then the user clicks a button for Edit/Delete.

I want this to be re-useable. So I have created a Method:

function dataTable() {

    var self = this;

    self.tableListUrl = "";
    self.gridObject = null;

    self.InitilizeAjaxTable = function (tableDiv, tableListUrl) {

        parameters = parameters || "";
        self.tableListUrl = tableListUrl;

        self.gridObject = $("#" + tableDiv).bootgrid({
            formatters: {
                "actions": function (column, row) {
                    return "";
                }
            },
            rowCount: [5, 10, 25, 50, -1],
            requestHandler: function (request) {

                var model = fleetMaintenance.filterModel.GetModel();
                model.Current = request.current;
                model.RowCount = request.rowCount;
                model.Search = request.searchPhrase;
                return JSON.stringify(model);
            },
            ajaxSettings: {
                method: "POST",
                contentType: "application/json"
            },
            ajax: true,
            url: self.tableListUrl,
        }).on("loaded.rs.jquery.bootgrid", function (e) {
            alert('Loaded');
        });
    }).on("click.rs.jquery.bootgrid", function (e, columns, row) {

});
},

self.RefreshTable = function () {
    self.gridObject.bootgrid("reload");
},

}

Then I can initialize my table using:

<script type="text/javascript">
    $(function() {
        var dt = new dataTable();

        dt.InitilizeAjaxTable("sitesList", '@Url.Action("SitesList","Sites")');
    });
</script>

HTML:

<table id="sitesList" class="table table-hover table-striped">
    <thead>
        <tr>
            <th data-column-id="iSiteId" data-visible="false" data-identifier="true" data-type="numeric" data-sortable="false">Site Id</th>
            <th data-column-id="sSiteName" data-order="desc">Site Name</th>
            <th data-column-id="sNotes">Notes</th>
            <th data-column-id="sAddress">Address</th>
            <th data-column-id="sCity">City</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>       

I know I can set the rowSelect and the selection to true.

I can bind the click event on the button, what I need to know is How can I append a button at the start of this table with data attributes?

Dawood Awan
  • 7,051
  • 10
  • 56
  • 119

4 Answers4

4

This one works for me:

$("#grid-header").find('.actions.btn-group').append('<button class="btn btn-primary" type="button">Edit <span class="icon glyphicon glyphicon-pencil"></span></button>');
Kachwahed
  • 542
  • 7
  • 17
3

This is how I've implemented my button to fit nicely with the bootgrid:

$("#grid-header").find('.actionBar').prepend('
    <button id="btnAdd" class="btn btn-primary pull-left" type="button">
        <span class="icon glyphicon glyphicon-plus"></span>
        Add
    </button>
');

It works nicely and it's pretty easy to customize your button in there.

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
  • My table header has id 'grid-data-header'. So I used $("#grid-data-header") instead of $("#grid-header") and it worked. – T.Shah Dec 24 '19 at 11:49
1

Okay so I extended the jquery-bootgrid Object and created a customDataTable Object.

All you have to do is copy/paste the following code in a JS file and link it to your website after linking jquery bootgrid JS file.

NOTE: I have added a custom requestHandler and responseHandler but you can edit this or remove it if you don't need it - as this is what I am using in my application.

(function($) {

  $.fn.customDataTable = function(options) {
    var namespace = ".rs.jquery.bootgrid";
    var settings = $.extend({
      tableListUrl: null,
      buttons: [],
      refreshTables: [],
      updateParameters: '',
      canSearch: true,
      rowCount: [10, 25, 50, -1],
      ajax: true,
      css: {
        actions: 'actions btn-group',
        dropDownMenu: 'dropdown btn-group'
      },
      searchSettings: {
        characters: 2
      },
      rowSelect: true,
      templates: {
        header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\"><div class='col-md-12 bootgridMessage'></div><div class=\"col-sm-12 actionBar\"><p class=\"{{css.search}}\"></p><p class=\"{{css.actions}}\"></p></div></div></div>"
      }

    }, options);

    if (!settings.canSearch) {
      settings.templates.header = "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\"><div class='col-md-12 bootgridMessage'></div><div class=\"col-sm-12 actionBar\"><p class=\"{{css.actions}}\"></p></div></div></div>";
    }



    var createButtons = function() {
      var buttons = settings.buttons;
      var htmlButtons = [];

      $.each(buttons, function(name, props) {
        var css = "";
        if (!props.enabled) {
          css = " hidden";
        }
        var tempBtn = $("<button/>", {
          text: props.Text, //set text 1 to 10
          id: "btn_" + props.Text,
          "class": props.css + " pull-left" + css,
          click: props.click
        }).attr({
          "style": "margin-right: 5px;"
        });

        htmlButtons.push(tempBtn);

      });
      return htmlButtons;
    };
    var buttons = createButtons();
    var parentDiv = $(this).parent().parent();
    var dt = $(this).bootgrid({
      css: settings.css,
      rowCount: settings.rowCount,
      selection: settings.rowSelect,
      rowSelect: settings.rowSelect,
      searchSettings: settings.searchSettings,
      converters: {
        datetime: {
          from: function(value) {
            return moment(value);
          },
          to: function(value) {
            var customDateTime = moment.utc(value);
            return customDateTime.format("DD/MM/YYYY HH:mm:ss");
          }
        },
        date: {
          from: function(value) {
            return moment.utc(value);
          },
          to: function(value) {
            var customDateTime = moment.utc(value);
            return customDateTime.format("DD/MM/YYYY");
          }
        }
      },
      requestHandler: function(request) {
        var model = {};

        model.Current = request.current;
        model.RowCount = request.rowCount;
        model.Search = request.searchPhrase;

        for (var key in request.sort) {
          model.SortBy = key;
          model.SortDirection = request.sort[key];
        }

        return JSON.stringify(model);
      },
      responseHandler: function(response) {
        return response;
      },
      ajaxSettings: {
        method: "POST",
        contentType: "application/json"
      },
      ajax: settings.ajax,
      url: settings.tableListUrl,
      templates: settings.templates
    }).on("selected" + namespace, function(e, row) {

    }).on("load" + namespace, function(e) {});

    for (var i = 0; i < buttons.length; i++) {
      parentDiv.find(".actionBar").prepend(buttons[i]);
    }
    return dt;
  };

}(jQuery));

And then I created the bootgrid tables like this:

var assetsList = $("#grid-data").customDataTable({
  ajax: false, // set to true to load data using Ajax
  buttons: {
    dlt: {
      Text: "Delete",
      css: "btn btn-danger",
      enabled: true, // false to hide button
      click: function() {
        alert('Delete clicked')
        var selectedId = assetsList.bootgrid("getSelectedRows")[0];
        if (selectedId == undefined) {
          alert('No Item Selected');
          return;
        }
      }
    },
    update: {
      Text: "Update",
      css: "btn btn-primary",
      enabled: true,
      click: function() {
        alert('update clicked')

      }
    }
  }
});

You can pass as many buttons as you need, and can also define the functionality they perform.

For Ajax Tables, just pass in the correct URL and set ajax to true:

var assetsList = $("#grid-data").customDataTable({
  tableListUrl: '/Controller/Action',
  ajax: true,

You can see a working example of this here: https://jsfiddle.net/mdawood1991/m5j722gz/

Dawood Awan
  • 7,051
  • 10
  • 56
  • 119
0

Use the jQuery prepend function after the table is loaded:

$('#sitesList tr').prepend(
     '<th>' +
         '<button type="button" testDate="' + yourData + '">' +
              'click me' +
          '</button>' +
     '</th>'
);

To add a button to the top of the table.

Sceptic
  • 1,659
  • 2
  • 15
  • 25