$(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(','));
});