Datatables in a Colorbox iframe with Selected Row Returned to Parent Window

by Thomas Beutel

I recently created a form where one of the questions was asking for a specific code (specifically, a NAICS code). The problem was that there are almost 20,000 codes to choose from, so it was not practical to use a pulldown. I hit upon the idea of using the wonderful Datatables table plugin for jQuery. I didn’t want the table to be in the form, so I decided to display it in a Colorbox iframe.

The challenge was how to report back the selected code. I decided to have datatables add a column of radio buttons and then use a regular button to report back the value to the parent window.

Here is how I set up the datatable:


<script>
$(document).ready(function() {
  $('#naics').DataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": "/main/NAICSTableData", // see Server Side Processing
    "createdRow": function ( row, data, index ) { // add radio buttons
    $('td', row).eq(0).html('<input name="codeid" value="'+data[1]+' '+data[2]+'" type="radio" class="code-select">');
    }
  });
  $('#use-selected').click( function() {
    var selected_code = $('input[name=codeid]:checked').val();
    parent.UpdateCode(selected_code); // this function must be defined somewhere in parent
    parent.jQuery.colorbox.close();
  });
});
</script>
<table id="naics" class="display" width="100%" cellspacing="0">
<thead>
<tr><th></th><th>Code</th><th>Description</th></tr>
</thead>
<tbody>
</tbody>
</table>
<input id="use-selected" type="button" value="Use Selected Code" />

The UpdateCode function in the parent window looks like this:


<script>
function UpdateCode(selected_code){  $('#naics-code').val(selected_code);
</script>
<input type="text" name="naics-code" id="naics-code" value="" />

Here is what the table looks like in its colorbox:

Screen Shot 2015-01-23 at 4.03.42 PM

Overall I’m really happy with the performance of the searching and the fact that the value is fed back to the form in the parent window.