Form tab flow - Select 2

Provides a way to make a funcional form tab flow when using select2 plugin

by Mateus Junges

HTML

<div ng-app="myApp" ng-controller="MyCtrl">
  <h1>Form Tab Flow with Select2</h1>
  City: <input type="text" id="city"><br>
State:     
<select
    id="PreviousState"
    name="PreviousState"
    class="form-control select2"
    ng-model="PreviousState"
    ng-options="state.abbreviation + ' - ' + state.name for state in states track by state.abbreviation"
  >
    <option value="">State</option>
  </select>
  <br>
Zip: <input type="text" id="zip">
</div>

JavaScript

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function($scope) { 
    $scope.states = STATES    
}]);



// automaticaly open the select2 when it gets focus
jQuery(document).on('focus', '.select2', function() {
    jQuery(this).siblings('select').select2('open');
});

// when the select2 closes advance focus to the next field
jQuery(document).ready(function() {
    jQuery(".select2").select2().on("select2:close", function(e) {
        var nextId = getNextFocusableFieldId(jQuery(this).attr('id'));
        // set focus to the next field
        jQuery('#' + nextId).focus().select();
    });
});

// return the id of the next focusable field
function getNextFocusableFieldId(idIn) {
    var focusables = jQuery("input, select, textarea");
    var reachedId = false;
    var id = '';
    var nextId = '';
    jQuery.each(focusables, function(index, value) {
        id = jQuery(this).attr('id');
        // if we reached the id last time set the nextId and exit each
        if (reachedId) {
            nextId = id;
            return false;
        }
        // if the ids match set the flag for the next iteration
        if (id == idIn) {
            reachedId = true;
        }
    });
    return nextId;
}

// data
var STATES = [{
  "name": "Alabama",
  "abbreviation": "AL"
}, {
  "name": "Alaska",
  "abbreviation": "AK"
}, {
  "name": "Arizona",
  "abbreviation": "AZ"
}, {
  "name": "Arkansas",
  "abbreviation": "AR"
}, {
  "name": "California",
  "abbreviation": "CA"
}, {
  "name": "Colorado",
  "abbreviation": "CO"
}, {
  "name": "Connecticut",
  "abbreviation": "CT"
}, {
  "name": "Delaware",
  "abbreviation": "DE"
}, {
  "name": "District Of Columbia",
  "abbreviation": "DC"
}, {
  "name": "Florida",
  "abbreviation": "FL"
}, {
  "name": "Georgia",
  "abbreviation": "GA"
}, {
  "name": "Hawaii",
  "abbreviation": "HI"
}, {
  "name": "Idaho",
  "abbreviation": "ID"
}, {
  "name": "Illinois",
  "abbreviation": "IL"
}, {
  "name": "Indiana",
 ...