Skip to content

Adding a NAICS code dropdown with Selectize

Adam Becker edited this page Oct 7, 2016 · 2 revisions

Uses the Code for America NAICS API: https://github.com/codeforamerica/naics-api

Live demo: http://output.jsbin.com/koqerozumu

Add the Selectize libraries

<link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.3/css/selectize.default.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.3/js/standalone/selectize.js"></script>

Add the Javascript

fr = new FormRenderer({"project_id":"xxx"});


fr.on('viewRendered', function(view){
  if (view.$el.attr('id') !== "fr_response_field_40528") return;
  
  view.$el.find('input[type=text]').selectize({
    valueField: 'code',
    labelField: 'code',
    searchField: ['code', 'description', 'title'],
    delimiter: ',',
    create: true,
    createFilter: /^[0-9]+$/,
    render: {
      option: function(item, escape) {
        if (item.title) {
          return '<div>' + escape(item.title) + ' (' + item.code + ')' + '</div>';  
        } else {
          return item.code;
        }
      }
    },
    load: function(query, callback) {
      if (!query.length) return callback();
      $.ajax({
        url: 'http://api.naics.us/v0/s',
        type: 'GET',
        dataType: 'json',
        data: {
            year: '2012',
            terms: query
        },
        error: function() {
          callback();
        },
        success: function(res) {
          callback(res);
        }
      });
    }
  }).on('change', function(){
    $(this).trigger('input')
  })
})