Search code examples
javascriptrazorjsgrid

Displaying booleans as checkboxes in jsgrid


I am using jsgrid to represent my data and for the boolean values I want to use checkboxes (the checkbox should be checked if the value is true and unchecked otherwise). The data is being fed into the grid through an ajax call:

        <div class="card-body">
            <div id="populationList"
                 class="jsgridpart"
                 data-part="@Url.Action("ListAjax", "PopulationCrm")"
                 data-parttype="jsgrid"
                 data-configaction="createAjaxListConfig"
                 data-updateevent="worksiteList">
            </div>
        </div>

And here's how I defined my fields:

fields: [

{ 
   name: "SerialNo", 
   type: "text" ,
   title : "@Html.DisplayNameFor(m => entity.SerialNo)" 
},
{ 
   name: "Model", 
   type: "text", 
   title : "@Html.DisplayNameFor(m => entity.Model)"
},
...

]

Here are the last 2 fields (these are checkboxes and these are the ones I want to be checked based on the value of the boolean):

{ 
   name: "Cva", 
   type: "checkbox", 
   width: 50, 
   title : "@Html.DisplayNameFor(m => entity.Cva)"
}, 
{ 
   name: "SL", 
   type: "checkbox", 
   css: function(item) {
      return "vl-green" + (item === true ? "checked" : "")
      }, 
   width: 50, 
   title : "@Html.DisplayNameFor(m => entity.ServiceLetters)" 
}

The current approach obviously doesn't work as the "item" parameter in not actually being fed anything (I tried console.log(item); and it just returned "0" always).

Does anyone know how I can display my booleans as checkboxes or at least how can I access the data that is being displaying in the current field?


Solution

  • I've found the solution, although not probably not the cleanest one. As far as I know jsgrid does not have boolean representation as checkbox implemented, so I used java script. First, on the fields I put type: "text" instead of type: "checkbox":

    { name: "Cva", type: "text", width: 50, title : "@Html.DisplayNameFor(m => entity.Cva)"},
                    { name: "ServiceLetters", type: "text", css: "vl-green", width: 50, title : "@Html.DisplayNameFor(m => entity.ServiceLetters)" }
                    
    

    And then I manipulated the element using js:

    checkboxes.each(function() {
                
                let content = $(this).text();
                if(content === "true") {
                    $(this).html(content + "<input type='checkbox' checked>");
                } else {
                    $(this).html(content + "<input type='checkbox'>");
                }
                
            });
    

    I also set the font-height to 0 on the text inside the div where the checkbox is going to be (I had to preserve the true/false text incase of refreshing, this step might not be necessary for some).

    This works fine. Although there's probably a better solution out there.