Search code examples
tabulatorstimulusjs

How to obtain user ids via checked checkboxes and send with Form submission


I have created a JSFiddle https://jsfiddle.net/cga_2019/ubjcx6ms/41/ representing users and their ids. I am using Tabulator with StimulusJS in a Rails 7 application.

I would like to ultimately grab user ids from each checkbox that has been checked and submit those user ids on form submission.

How do I add user id values to the checkboxes? How would I grab the checked user ids and submit them?

Thank you for any help. Chris

HTML

<html>
  <head>
  <link href="https://unpkg.com/tabulator-tables@5.1.8/dist/css/tabulator.min.css" rel="stylesheet">
 <script type="text/javascript" src="https://unpkg.com/tabulator-tables@5.1.8/dist/js/tabulator.min.js"></script>
  </head>

<body>

  <input type="hidden" id="projId" name="projId" value="7">

  <div data-controller="tabulator">
    <div data-tabulator-target="table"></div>
  </div>
</body>
</html>

JavaScript

import { Application, Controller } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
const application = Application.start()

application.register("tabulator", class extends Controller{
  static get targets() {
    return ["table"]
  }
  
  connect() {
    // this.tableTarget.innerHTML = "Put a tabulator table here!"

    this.tabledata = [
      {id:1, first_name:"Oli", last_name:"Bob", netid:"obob"},
      {id:2, first_name:"Mary", last_name:"May", netid:"mmay"},
      {id:3, first_name:"Christine", last_name:"Lobowski", netid:"clobowski"},
      {id:4, first_name:"Brendon", last_name:"Philips", netid:"bphilips"},
      {id:5, first_name:"Margret", last_name:"Marmajuke", netid:"mmarmajuke"},
      {id:6, first_name:"John", last_name:"Wayne", netid:"jwayne"},
    ];

    this.table = new Tabulator(this.tableTarget, {
      //height: 205,
      pagination: true,
      paginationSize: 3,
      data: this.tabledata,
      // ajaxURL: "http://localhost:3000/users_projects/users",
      layout: "fitColumns",
      columns: [
        {formatter:"rowSelection",titleFormatter:"rowSelection",hozAlign:"center",
          headerSort:false,width:50,cellClick:function(e, cell){cell.getRow().toggleSelect();}},
        {title:"ID", field:"id", width:50},
        {title:"Last Name", field:"first_name", width:150},
        {title:"First Name", field:"last_name"},
        {title:"NetID", field:"netid"},
      ],
    })
  }
  
})

Solution

  • Use table.getSelectedData()

    Official Docs

    Working JSFiddle