Jason Towne
Jason Towne

Reputation: 8050

How do I set the selected value of a drop down list in a jTemplate?

I'm using jTemplates to create several elements of my form based on data returned from the server. I'm able to set the value of input fields without any problems but I'm having trouble setting the selected value of a drop down list.

I've tried using a jQuery selector to set the value within the template itself which didn't work. It just added a [object Object] right above my drop down. I've also tried using a bunch of {#if} statements (see below) which also hasn't worked.

Any thoughts?

Calling jTemplate:

<script type="text/javascript">
  $('#my_container').setTemplateURL("templates/MyTemplate.htm", [], { filter_data: false, runnable_functions: true }).processTemplate(data);
</script>

My simplified template:

<table id="expense_table_{$T.ID}">
  <tr>
    <td width="80">
      <input type="text" id="my_amount" class="amount numbersOnly" value="{$T.Amount}" />
    </td>
    <td width="180">
      <select id="my_type" class="my-type">
        {#if $T.MyTypeID == 1} 
          <option value="1" selected>Option 1</option>
        {#else}
          <option value="1">Option 1</option>
        {#/if}
        {#if $T.MyTypeID == 2} 
          <option value="2" selected>Option 2</option>
        {#else}
          <option value="2">Option 2</option>
        {#/if}
        {#if $T.MyTypeID == 3} 
          <option value="3" selected>Option 3</option>
        {#else}
          <option value="3">Option 3</option>
        {#/if}
        {#if $T.MyTypeID == 4} 
          <option value="4" selected>Option 4</option>
        {#else}
          <option value="4">Option 4</option>
        {#/if}        
      </select>
    </td>
  </tr>
</table>

Upvotes: 0

Views: 628

Answers (1)

Jason Towne
Jason Towne

Reputation: 8050

It turns out the template I posted with all of the {#if} statements in my original question works after all. It sure doesn't seem like an ideal solution though, especially for drop down lists with a lot of options. I'll mark this question as answered unless someone can come up with a better solution.

Upvotes: 0

Related Questions