Search code examples
javascriptcheckboxlistjs

list js with checkboxes


Im using List js on html list with checkboxes and trying to populate it with values object as in :

var values = [
  {
    id: 12,
    action: 'a',
...
  },
  {
    id: 13,
    action: 'b',
...
  }
];

HTML :

<div id="users">
  <ul class="list">
    <li>
      <span class="id"></span>
      <span class="action"></span >
      <input class="required" type="checkbox">Required
    </li>
  </ul>

</div>

and initializing as in :

new List('users', options, values);

How to make it work?

Just to clearify Im missing how to complete values object and how to define option object so that i could init the check state of the checkboxes initially.


Solution

  • Create an options variable and add object { name: 'required', attr: 'checked'} with other property names. Pass the options as a parameter to the new list created.

    Update:

    Based on your comment, I don't think it is possible using the list.js, if you are willing to add Jquery to your application, this is a small hack you could incorporate.

    Add $("input[checked='false']").prop('checked', false); to your code once the list is created.

    Note: You wanna add the above line asynchronously, once the entire list is populated, in case you are working with a lot of data.

    Demo -

    var options = {
      valueNames: ['id', 'action', {
        name: 'required',
        attr: 'checked'
      }],
      item: 'user-item'
    };
    
    var values = [{
        id: 12,
        action: 'a',
        required: false
      },
      {
        id: 13,
        action: 'b',
        required: true
      }
    ];
    
    var userList = new List('user-list', options, values);
    
    //Once the entire list is populated, set all checked='false' checkboxes to unchecked state.
    $("input[checked='false']").prop('checked', false);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
    
    <div id="user-list">
      <ul class="list"></ul>
    </div>
    
    <div style="display:none;">
      <!-- A template element is needed when list is empty, TODO: needs a better solution -->
      <li id="user-item">
        <span class="id"></span>
        <span class="action"></span >
        <input class="required" type="checkbox" />Required
      </li>
    </div>