bind template data for select option
let's say i have a jquery template with this html code:
<div>
<span id="myfirstname"></span>
<select id="mygender" multiple="multiple">
<option value="1">-select-</option>
<option value="2">Male</option>
<option value="3">Female</option>
<option value="4">NotSpecified</option>
</select>
</div>
my json looks like : { "FirstName": "John", "Gender": "Male" };
I can bind myfirstname using ${FirstName} but how do i bind the drop down value? I used ${Gender} but that displays just the value and NOT the drop down list with the "开发者_如何学CMale" option selected.
One option would be something like:
<div>
<span id="myfirstname">${FirstName}</span>
<select id="mygender" multiple="multiple">
<option value="1">-select-</option>
<option value="2" {{if Gender == 'Male'}}selected="selected"{{/if}}>Male</option>
<option value="3" {{if Gender == 'Female'}}selected="selected"{{/if}}>Female</option>
<option value="4" {{if Gender == 'NotSpecified'}}selected="selected"{{/if}}>NotSpecified</option>
</select>
</div>
If that is too verbose, then you could create a function to do the match like:
function match(value, choice) {
return value === choice ? "selected='selected'" : "";
}
Then do:
<div>
<span id="myfirstname">${FirstName}</span>
<select id="mygender" multiple="multiple">
<option value="1">-select-</option>
<option value="2" ${match(Gender, 'Male')}>Male</option>
<option value="3" ${match(Gender, 'Female')}>Female</option>
<option value="4" ${match(Gender, 'NotSpecified')}>NotSpecified</option>
</select>
</div>
精彩评论