Skip to content

Instantly share code, notes, and snippets.

@LukeChannings
Last active August 5, 2024 20:15
Show Gist options
  • Save LukeChannings/6173ab951d8b1dc4602e to your computer and use it in GitHub Desktop.
Save LukeChannings/6173ab951d8b1dc4602e to your computer and use it in GitHub Desktop.
A select helper for handlebars
Handlebars.registerHelper("select", function(value, options) {
return options.fn(this)
.split('\n')
.map(function(v) {
var t = 'value="' + value + '"'
return ! RegExp(t).test(v) ? v : v.replace(t, t + ' selected="selected"')
})
.join('\n')
})
@LukeChannings
Copy link
Author

Example usage:

<select>
{{#select "Bar"}}
<option value="">Select an option</option>
<option value="Foo">Foo</option>
<option value="Bar">Bar</option>
{{/select}}
</select>

Outputs:

<select>
<option value="">Select an option</option>
<option value="Foo">Foo</option>
<option value="Bar" selected="selected">Bar</option>
</select>

@FossPrime
Copy link

Here's a version that will pass ESLint...

Handlebars.registerHelper('select', function (value, options) {
  return options.fn()
    .split('\n')
    .map(function (v) {
      var t = 'value="' + value + '"';
      return RegExp(t).test(v) ? v.replace(t, t + ' selected="selected"') : v;
    })
    .join('\n');
});

@tjtarunkumar
Copy link

How to create it for multiple selection.

@neeraj87
Copy link

neeraj87 commented Dec 6, 2018

How to create it for multiple selection.

multiselect: function (selected, option) {
        if(selected == undefined) {
            return '';
        }
        return selected.indexOf(option) !== -1 ? 'selected' : '';
    }
<div class="form-group col-6">
            <label for="booking_type">Booking Type</label>
            <select name="booking_type" id="booking_type" class="form-control" multiple>
                <option value="one_way_transfer" {{{multiselect ptb.booking_type "one_way_transfer"}}}>One Way Transfer</option>
                <option value="two_way_transfer" {{{multiselect ptb.booking_type "two_way_transfer"}}}>Two Way Transfer</option>
                <option value="nightclub_tour" {{{multiselect ptb.booking_type "nightclub_tour"}}}>Nightclub Tour</option>
                <option value="kids_bus_party" {{{multiselect ptb.booking_type "kids_bus_party"}}}>Kids Bus Party</option>
            </select>
        </div>

@vimtor
Copy link

vimtor commented Jul 19, 2019

Worked like a charm! Thanks.

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