<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",
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.