Created
June 21, 2013 16:38
-
-
Save lsamayoa/5832509 to your computer and use it in GitHub Desktop.
A simple 10 mins jquery based expandable countries selector.
Ex: http://jsfiddle.net/leonel0101/UyfxM/6/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
var makeExpandableCountriesSelector = function (selector, def, aditional) { | |
// LOCAL CONSTANTS | |
var LESS_VALUE = 'less', | |
MORE_VALUE = 'more'; | |
// Our model | |
var countries = def, | |
more = true, | |
less = false; | |
// Utility method to render an option simple html | |
var renderOption = function (value, text) { | |
return '<option value="' + value + '">' + text + '</option>'; | |
}; | |
// Updates the select element | |
var updateCountries = function () { | |
// We render the select country text. | |
var rendered = renderOption('void', 'Select Country...'); | |
// We reduce our model and render each option | |
rendered += countries.reduce(function (prev, curr, idx) { | |
if (idx == 1) prev = '<option value="' + prev + '">' + prev + '</option>'; | |
return prev + renderOption(curr, curr); | |
}); | |
if (more) rendered += renderOption(MORE_VALUE, 'Show More...'); | |
if (less) rendered += renderOption(LESS_VALUE, 'Show Less...'); | |
$(selector).html(rendered); | |
}; | |
// Event delegation | |
$(selector).change(function () { | |
if ($(this).children(":selected").val() === MORE_VALUE) { | |
// Change the model | |
countries = def.concat(aditional); | |
more = false; | |
less = true; | |
// Update the View | |
updateCountries(); | |
} | |
if ($(this).children(":selected").val() === LESS_VALUE) { | |
// Change the Model | |
countries = def; | |
more = true; | |
less = false; | |
// Update the View | |
updateCountries(); | |
} | |
}); | |
// Start! | |
updateCountries(true); | |
}; | |
// Usage: | |
// makeExpandableCountriesSelector("select#test", 'Guatemala,El Salvador, Honduras'.split(','), 'Uruguay,Chile,Panama,Brazil,Argentina'.split(',')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment