// JSON Array of Towns.. In Rails: <%= @towns = Town.all.to_json %> var TOWNS = [ { town: "Abbeville city", id: 1 }, { town: "Adamsville city", id: 2 }, { town: "Addison Town", id: 3 } ]; $(document).ready(function() { $('#postcard_city').bind('change', updateStateValue); // Function takes a town string and returns a town id from the TOWNS json array. var findTown = function(townName) { var townIdToReturn = false; for (var i = 0; i < TOWNS.length; i++) { if (TOWNS[i].town == townName) { townIdToReturn = TOWNS[i].id; break; } } return townIdToReturn; } // the function that gets called on the bind event... var updateStateValue = function(event) { var town = $('#postcard_city').val(); var id = findTown(town); if (!id) { $('#hidden_town_id').html(""); } else { $("#hidden_town_id").html(""); } } });