Created
August 28, 2012 18:45
-
-
Save areichman/3502068 to your computer and use it in GitHub Desktop.
Rails-like options_for_select helper for Handlebars
This file contains hidden or 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
// Create a set of HTML option tags for each of the supplied inputs. If the inputs are arrays | |
// themselves, it is assume they are of the form [displayName, value]. | |
// | |
// e.g. | |
// directions = ['North', 'South'] | |
// {{options_for_select directions}} | |
// | |
// results in: | |
// <option>North</option> | |
// <option>South</option> | |
// | |
// e.g. | |
// directions = [['North', 'n'], ['South', 's']] | |
// {{options_for_select directions}} | |
// | |
// results in: | |
// <option value="n">North</option> | |
// <option value="s">South</option> | |
// | |
// To set the default selected value in the list, pass a second value with | |
// the desired value. | |
// | |
// e.g. | |
// directions = [['North', 'n'], ['South', 's']] | |
// selected = 'n' | |
// {{options_for_select directions selected}} | |
// | |
// results in: | |
// <option value="n" selected="selected">North</option> | |
// <option value="s">South</option> | |
// | |
Handlebars.registerHelper('options_for_select', function(items, selected) { | |
var output = '', display, value; | |
for (var i = 0; i < items.length; i++) { | |
if (items[i] instanceof Array) { | |
display = items[i][0]; | |
value = items[i][1]; | |
} else { | |
display = value = items[i]; | |
} | |
if (value == selected) { | |
output = output + '<option value="' + value + '" selected="selected">' + display + '</option>'; | |
} else { | |
output = output + '<option value="' + value + '">' + display + '</option>'; | |
} | |
} | |
return new Handlebars.SafeString(output); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment