1

I am using jQuery DataTables plugin for displaying data. Here I have a column with checkbox which should be checked or unchecked according to the values from the database, i.e. if the value from the db is true checkbox should be checked and if value from db is false checkbox should be unchecked.

Here is what I have tried so far.

table = $("#dataTableMenuRole").dataTable({
        "ajax": {
            "url": "@Url.Action("LoadGridView", "MenuSettings")",                
            "method": "POST",
            "dataType": "json",
            "data": function (d) {
                d.roleId = $("#ddlRoles").val()
            }
        },
        columns: [
            { "data": "MenuName" },
            { "data": "CanAdd" }               

        ],            
        "bProcessing": true,
        "aoColumnDefs": [{
            "targets": 1,
            "bSortable": false,
            "mRender": function (data, type, full, meta) {
                return '<input type="checkbox" class="minimal" checked="'+data+'"/>'
            }
        }]
    });

The JSON returned from the db is

{"data":[{"MenuName":"Roles","CanAdd":true},{"MenuName":"Menu","CanAdd":true},{"MenuName":"ServiceTax","CanAdd":false}]}
Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
ksg
  • 3,927
  • 7
  • 51
  • 97

1 Answers1

1

CAUSE

You define checked attribute despite the value in data and checkboxes will be always checked.

SOLUTION

Use the following code instead:

"mRender": function (data, type, full, meta) {
    return '<input type="checkbox" class="minimal"' + (data ? ' checked' : '') + '/>';
}

DEMO

See this jsFiddle for code and demonstration.

Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
  • Thanks for the reply.I think it should work and will vote after implementing it.Meanwhile if possible please clarify my another concern which is raised in [StackOverflow](http://stackoverflow.com/questions/32760613/jquery-datatable-is-it-possible-to-bind-href-property-of-link-with-razor-syntax) regarding using `href` attribute dynamically using JqueryDatatables – ksg Sep 25 '15 at 05:33
  • @ksg, your another question already has a correct answer so I just voted it up. – Gyrocode.com Sep 25 '15 at 11:03
  • Thanks for your answer mate.I am curious to know what is the importants of brackets`()` here .`(data ? ' checked' : '') ` – ksg Sep 25 '15 at 13:00
  • 1
    @ksg, brackets allow clause surrounded to be executed first, see [grouping operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping). – Gyrocode.com Sep 25 '15 at 13:11
  • @Gyrocode.com does this two way binding? so if i submit my form i could get the value of binded checkbox ? – Khalid Nov 15 '20 at 06:47
  • https://stackoverflow.com/questions/64841640/jquery-datatable-alway-showing-the-initially-checked-or-uncheck-values-only – Khalid Nov 15 '20 at 06:48