Search code examples
checkboxbootstrap-table

Setting checkbox state in HTML (checked/unchecked)


this is my table:

https://live.bootstrap-table.com/code/MajesticGray/15539

The checkbox column is rendered this way (given the user id is 2):

<input data-index="0" name="project[users][]" type="checkbox" value="2" checked="checked">

Now, that's ok but I want only some checkboxes to be checked on page load, so I took a look at the docs: https://bootstrap-table.com/docs/api/column-options/#checkbox

and it says that:

If a value is given, the checkbox is automatically checked. Its also possible to check/uncheck the checkbox by using a formatter (return true to check, return false to uncheck).

But I can't get this working. I tried data-formatter="() => false;" on <td>, to no avail.

Could you provide an example, please?


Solution

  • The data-formatter option actually only works on columns as far as I know, but it can indeed be used to achieve what you're wanting.

    I modified your example to add a formatter called checkFormatter and the corresponding function. You could modify this function as needed for your check/uncheck logic for every row. Formatters are really quite powerful!

    A quick overview of the changes:

    First, add the formatter to the column.

    <th data-field="id" data-checkbox="true" data-formatter="checkFormatter"></th>
    

    Then, create a function with the same name as the formatter.

      function checkFormatter(value, row, index) {
        if (index === 1) {
          return {
            checked: false
          }
        }
        //return value
      }
    

    I passed more parameters than needed, just to show what is possible. Also, you could return some other value in the commented out line if the row doesn't meet the condition for unchecking.

    Not knowing the full table generation code, index is just set to 1 (the second row) but it's entirely possible to also check something like if(row.id == 2) (another example with this change) which would use the value of the id column in your table.

    This official example shows how to use a formatter to check/uncheck a checkbox in this way.