Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Last active May 29, 2024 09:19
Show Gist options
  • Save codeBelt/2e3db2ae6db24e86a9a6 to your computer and use it in GitHub Desktop.
Save codeBelt/2e3db2ae6db24e86a9a6 to your computer and use it in GitHub Desktop.
Select & Multi Select Handlebar Block Helper
/**
* Sets the 'selected' property on the select option(s) when the value is passed in.
*
* @method selectHelper
* @example
* // selectValue = "69"
* // selectValue = "69,70,71"
* <select>
* {{#selectHelper selectValue}}
* <option value="Completed">Completed</option>
* <option value="OverDue">OverDue</option>
* <option value="SentToPayer">SentToPayer</option>
* <option value="None">None</option>
* {{/selectHelper}}
* </select>
*/
Handlebars.registerHelper('selectHelper', function(selected, options) {
var html = options.fn(this);
if (selected) {
var values = selected.split(',');
var length = values.length;
for (var i = 0; i < length; i++) {
html = html.replace( new RegExp(' value=\"' + values[i] + '\"'), '$& selected="selected"');
}
}
return html;
});
@yannisalexiou
Copy link

If anyone gets

selected.split is not a function

you may need to convert selected parameter to string first. So add the below line of code after var html = options.fn(this);
var selected = selected + '';

@jbender0
Copy link

You're a lifesaver! Thank you so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment