YUI Datatable - select all with checkbox column

I am using YUI (version 2.4.1) datatable for tabular data rendering. I needed to allow the users to have the ability to select one or more rows using checkboxes and then submit them to the server for further action. Up to this point you can find sample code on YUI website or other sites if you search around.


For a better user experience I also needed to give them links to 'Select All' and 'Unselect All' which did exactly that. This I was not able to find on the web (I am sure it is there somewhere). Since I finally figured it out, I thought it only fair to blog-it so others can find. Code is quite simple.

In the sample below I will only highlight the code necessary to make this happen. For more details on YUI datatable refer to Yahoo site.

To start off lets add a check box to the table. In the sample below the first column is the check box column.

myColumnDefs = [
     {key:"checked",label:"", width:"30", formatter:YAHOO.widget.DataTable.formatCheckbox},
     {key:"id", label:"ID",sortable:true, resizeable:true, width:"50"},
     {key:"name", label:"Name",sortable:true, resizeable:true, width:"250"},
     {key:"netamount", label:"Amount",sortable:true,resizeable:true,width:"100", formatter:YAHOO.widget.DataTable.formatCurrency}

];


myDataSource.responseSchema = {
        resultsList: "records",
        fields: [
             {key:"checked", parser:YAHOO.util.DataSource.parseBoolean},
             {key:"id", parser:YAHOO.util.DataSource.parseNumber},
             {key:"name", parser:YAHOO.util.DataSource.parseString},
             {key:"amount", parser:YAHOO.util.DataSource.parseNumber}
           ]
      };


In my case the data is coming via. JSON and I need the default case to be select all. Thus my JSON result set will have checked = true for all rows.

Next here is the code for 'select all' and 'unselect all'. You can be smarter about this and use one function if you care.
 function selectAll() {
        records = dataTable.getRecordSet().getRecords();
   for (i=0; i < records.length; i++) {
        dataTable.getRecordSet().updateKey(records[i], "checked", "true");
    }
   dataTable.refreshView();
   return false;
}
   
function unselectAll() {
        records = dataTable.getRecordSet().getRecords();
   for (i=0; i < records.length; i++) {
        dataTable.getRecordSet().updateKey(records[i], "checked", ""); 
   }
   dataTable.refreshView();
   return false;
}

The links on the web page.
<a id="selectall" href="#" onclick="return selectAll();">Select All</a> &nbsp;|&nbsp;
<a id="unselectall" href="#" onclick="return unselectAll();">Unselect All</a>




 del.icio.us  Stumbleupon  Technorati  Digg 

 

What did you think of this article?




Trackbacks
  • Trackbacks are closed for this entry.
Comments

  • 3/12/2008 7:01 AM hemant wrote:
    hi ,
    i tried u r code for selecting all fields but does not work for me it says selectall not define .it does not find the function selectall().
    plz help me
    thanks
    Reply to this
    1. 3/13/2008 7:16 PM Mathew Thomas wrote:
      Make sure the case is right for the function names. Should be selectAll() and unselectAll().

      Reply to this
      1. 3/17/2008 6:24 AM hemant wrote:
        hi ,
        thanks ,it;s working now .
        and one more change "dataTable.refreshView()"
        is now "dataTable.render();"

        yhanks bye
        Reply to this
  • 3/17/2008 6:27 AM hemant wrote:
    hi again
    what if i wants to check which one is checked and which one is not .
    bye
    Reply to this
    1. 3/17/2008 5:39 PM Mathew Thomas wrote:
                  this.myDataTable.subscribe("checkboxClickEvent", function(oArgs){
                      var elCheckbox = oArgs.target;
                      var elRecord = this.getRecord(elCheckbox);
                      var name = elRecord.getData("name");
                      if (elCheckbox.checked) {
                          AsyncRequest.call('addToServerSelectedList.action?',
                                  NoOpCallback.handleSuccess, NoOpCallback.handleFailure,
                                  NoOpCallback, "id="+elRecord.getData("id"));
                          MyList.add(name);
                      }
                      else {
                          AsyncRequest.call('removeFromServerSelectedList.action?',
                                  NoOpCallback.handleSuccess, NoOpCallback.handleFailure,
                                  NoOpCallback, "id="+elRecord.getData("id"));
                          MyList.remove(name);
                      }
                      //alert("Checkbox was " + (elCheckbox.checked ? "" : "un") + "checked for " + name);
                      this.myDataTable.selectRow(elRecord);
                  });

      This code I got from yui samples...i tweaked it for my needs. As u check/uncheck boxes this code is called. I do 2 things....
      1. call a server side action to collect user selections...same when they uncheck
      2. also i wrote a quick list class in js to hold the selections on the client...if u care for that here is the code ...



      var MyList = {
          init: function() {
              MyList.items = new Object();
          },
          add: function(v) {
              MyList.items[v] = v;
          },
          contains: function(v) {
              return (MyList.items[v] != undefined && MyList.items[v] != null);
          },
          remove: function(v) {
              if (MyList.contains(v)) {
                  MyList.items[v] = null;
              }
          },
          length: function() {
              len = 0;
              for (selectedItem in this.items) {
                  if (MyList.items[selectedItem] != undefined && MyList.items[selectedItem] != null) {
                      len++;
                  }
              }
              return len;
          },
          toString: function() {
              s = "";
              for (selectedItem in this.items) {
                  if (MyList.items[selectedItem] != undefined && MyList.items[selectedItem] != null) {
                      s += selectedItem + ",";
                  }
              }
              if (this.length() > 0) {
                  alert("" + this.length() + " row(s) selected:" + s);
              }
              else {
                  alert("No rows selected.");
              }
              return s;
          }
      };

      make sure to call iniit once before using this.
      MyList.init();
      MyList.add("1");
      MyList.add("2");
      MyList.add("3");

      MyList.toString();

      MyList.remove("2");
      MyList.toString();

      Reply to this
  • 5/9/2008 3:36 PM Dan wrote:
    Could you publish an example file that uses this technique. I'm having a hard time getting this to work. In the selectAll() function I am getting an error saying that the this.myDataTable does not have any attributes. Obviously, I am missing something basic.

    Thanks for any help.
    Reply to this
  • 7/22/2008 10:47 AM gackiem wrote:
    hi Mathew Thomas,
    Your code above is worked OK, but the speed is slowly (i've tested your code with a data table have 50 rows in IE6, a little faster for others browser like FF2, Opera9.5 and Safari 3.1).
    Reply to this
  • 8/11/2008 10:27 PM CB wrote:
    This is a great example... thank you!

    I was wondering how to loop through a YUI DataTable column with Checkboxes to get the checked flag and a string value associated with the checkbox.
    Reply to this
  • 8/11/2008 10:33 PM CB wrote:
    I corrected my email and wanted to say that I am updating a series of filters on another DataTable.
    Reply to this
  • 1/19/2009 9:55 PM Greg wrote:
    Great example. Here are the functions with arguments for the table and the column name. I also renamed the functions so they would appear together in large code.

    function markAllRowsChecked(oTable, columnName) {
    records = oTable.getRecordSet().getRecords();
    for (i=0; i < records.length; i++) {
    oTable.getRecordSet().updateKey(records[i], columnName, "true");
    }
    oTable.render();
    }

    function markAllRowsUnchecked(oTable, columnName) {
    records = oTable.getRecordSet().getRecords();
    for (i=0; i < records.length; i++) {
    oTable.getRecordSet().updateKey(records[i], columnName, "");
    }
    oTable.render();
    }
    Reply to this
  • 3/23/2009 6:14 AM Ranju wrote:
    Hi Mathew,

    Just wanted to tell you THANKS. I was stuck with some of the functionality (especially adding check box) that I had to implement in my app. And your code really helped me to sort out things.

    Thanks
    Ranju
    Reply to this
  • 9/2/2009 9:40 AM Johannes wrote:
    Thanks for the hint! I didn't know the updateKey-Method. Great. Thanks.
    Reply to this
  • 2/24/2010 4:14 AM Manasi wrote:
    I am new to yui.But i wanted to know how the dataTable is accessible in the custom function 'CheckAll'?
    Reply to this
    1. 2/26/2010 11:23 PM Mathew Thomas wrote:
       unfortunately its been a while since I used the dataTable and since then YUI has had newer releases.

      Reply to this
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.