Using jQuery Templates to .appendTo() an <option> on a <select> list via .render()

I couldn’t find a good example that shows how to achieve this, so I thought I would quickly outline the process along with some “gotchas” I encountered.

First, an outline of the technology/components/elements I’m talking about:

  • Templates is the Microsoft proposed templating solution for jQuery.
  • This library can be obtained from github.
  • I want to add <options> on the <select> list.
  • I want to achieve this using the .render() method demonstrated on ScottGu‘s blog post on jQuery Templates.
  • In conjunction with using the .appendTo() method in jQuery.

The desired end result, outputting items into the select list via jQuery:
Select List

There’s actually several similar ways this can be achieved as can be seen on this StackOverflow question. I’ve put a summary of this post as an answer on that question also.

To add scope to this post, here is a quote from Scott Gu’s blog post on the purpose of the templating system.

Client-side templates enable jQuery developers to easily generate and render HTML UI on the client. Templates support a simple syntax that enables either developers or designers to declaratively specify the HTML they want to generate. Developers can then programmatically invoke the templates on the client, and pass JavaScript objects to them to make the content rendered completely data driven. These JavaScript objects can optionally be based on data retrieved from a server.

At this point I’m going forward on the assumption you now have a rough understanding of the purpose of templating so I can focus primarily on getting this to work with a <select> list.

The first step is to setup the appropriate template structure. In this scenario, it’s the <option> block with the ‘value’ and ‘text’ properties needing substitution. The syntax for the substitution variables is wrapped by the two opening curly-braces and an equal sign, it’s name then followed by 2 closing curly-braces. A note here as this is JavaScript performing the substitutions, it is in fact case sensitive.

<script id="templateOptionItem" type="text/html">
    <option value=\'{{= Value}}\'>{{= Text}}</option>

Zoom in, enhance!

Ensure you escape single quotes
Ensure you escape single quotes otherwise the templating render() action will fail.

The next step is to “fetch” your data (input data), in my real world example this comes back as JSON. But for now let’s just hard code the data array.

    function renderTest() {

        var someData = [
            { Text: "one", Value: "1" },
            { Text: "two", Value: "2" },
            { Text: "three", Value: "3"}];

        //on the template, apply the render with the data input, and then append to the html element.

That last line with the .render() and .appendTo() is where the elegance lies, the set-up of reusable templates is extracted out of the actual call to map the data to the html elements. There are more features in the templating library, so check out this post for more examples.

The aim is to keep this post on the very narrow topic of just applying to a select list. So the actual implementation of the ajax-y request and response of JSON will come in a future post. The impact on the actual templating logic is trivial and limited to the what you pass to the .render() call.

Summary of the gothcas:

  • Escape your quotes (single and doubles).
  • The template must be in it’s own script block, not as a JavaScript var (string). Not sure why that is, I’m still investigating.
  • Ensure your selectors are working.
  • Ensure your output is wrapped in valid html elements, at the least a <div>.
  • Template place holders are case-sensitive.

Published by Nick Josevski

Software Engineer at Octopus Deploy

2 thoughts on “Using jQuery Templates to .appendTo() an <option> on a <select> list via .render()

  1. Hey Nick,

    Have you ever dealt with a situation, where the select box has already been populated with options, let’s say on the server, but you need to select the right option through jQuery tmpl plug-in. If you did, please let me know how you did it.



    1. Sorry Zen,
      I haven’t tried a situation like that, I would be looking for an alternate approach if it’s already populated, but that all depends on how your application is structured.

      Have you tried asking a question on Stackoverflow with more details and examples of what you’ve tried, send me the link if you do ask the question.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: