Reputation: 115
I'm using the jQuery Template plugin (jquery.tmpl.js) and for the most part I understand it, but I'm really struggling to get it to work with elements where the options for the select element come from one JSON object but the selected value comes from the property of another. Below is my code:
The HTML:
<fieldset id="userFieldset">
<script id="userTemplate" type="text/x-jquery-tmpl">
<label for="TitleId">Title</label>
<select value="${TitleId}" id="TitleId" name="TitleId">
{{tmpl(titles) "#titleTemplate"}}
</select>
<label for="UserName">Name</label>
<input type="text" name="UserName" id="UserName" class="text ui-widget-content ui-corner-all" value="${UserName}"/>
<label for="Password">Password</label>
<input type="password" name="Password" id="Password" class="text ui-widget-content ui-corner-all" value="${Password}"/>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<option value="${ID}">${Value}</option>
</script>
</fieldset>
The javascript:
var titles = Sys.Serialization.JavaScriptSerializer.deserialize("[{\"ID\":3,\"Value\":\"Mr\"}, {\"ID\":2,\"Value\":\"Ms\"}, {\"ID\":1,\"Value\":\"Doctor\"}]", false);
function showEditUser(user) {
$("#userFieldset").empty();
$("#userTemplate").tmpl(user).appendTo("#userFieldset");
$("#userDialog").dialog("open");
}
However, this doesn't change the selected value of the TitleId select. Any help would be greatly appreciated.
Upvotes: 2
Views: 7249
Reputation: 114792
You need to set the selected attribute on your option element.
One way to do this is to pass options to {{tmpl}} that contains your TitleId, so that you can compare it with the ID variable of the title object.
This would look something like:
<fieldset id="userFieldset">
<script id="userTemplate" type="text/x-jquery-tmpl">
<select id="TitleId" name="TitleId">
{{tmpl(titles, { selectedId: TitleId }) "#titleTemplate"}}
</select>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<option {{if ID === $item.selectedId}}selected="selected"{{/if}} value="${ID}">${Value}</option>
</script>
</fieldset>
So, you pass TitleId
to your child template and call it selectedId
(you could of course just call it TitleId too). You access it in the child template off of the $item
object like $item.selectedId
and use it to determine if the selected
attribute should be set on the option
element.
Sample here: http://jsfiddle.net/rniemeyer/YCQ9S/
Upvotes: 4
Reputation: 27441
"value" is not a valid attribute for <select>
HTML tag. You have to set the "selected" attribute on the <option>
itself to make it selected. Try something like this:
<script id="titleTemplate" type="text/x-jquery-tmpl">
<option value="${ID}" selected="${checkSelected(this.data.ID)}">${Value}</option>
</script>
<script>
function checkSelected(id)
{
// logic to determine if this id should be the selected one.
return "selected"; //or not
}
</script>
Upvotes: 1