I would like to initialize a select
with an initial value. I have a Json object returned from my backend like this one:
[{Nom:"xxx", TypeIld:1, ....},{Nom:"xxx", TypeId:1, ....}]
I have an array of typeIds declared like this :
[{ Nom: "Plats", TypeId: 0 },
{ Nom: "Crudités", TypeId: 1 },
{ Nom: "Tartes Salées", TypeId: 2}]
I would like to display all my records in a table with a select for the typeId initialized to the correct value.
Here is my code:
<form class="PlatsCuisinesEditor">
<table data-bind="visible: platscuisines().length > 0">
<thead><tr><th></th><th>Nom</th><th>Description</th><th>Prix</th><th>Frequence</th><th>Type</th><th></th></tr></thead>
<tbody data-bind='template: { name: "PCRowTemplate", foreach: platscuisines }'></tbody>
</table>
<br />
<div style="margin-top:10px;">
<button data-bind="enable: platscuisines().length > 0" type="submit">Enregistrer les plats</button>
</div>
</form>
<script type="text/html" id="PCRowTemplate">
<tr>
<td><input class="required" data-bind="value: Nom, uniqueName: true"/></td>
<td>
<select data-bind="options: viewModel.platstypes, optionsText:'Nom'"></select>
</td>
</tr>
</script>
<script type="text/javascript">
var initialData = @Html.Raw(Json.Encode(ViewBag.JsonPlats));
var dataFromServer = ko.utils.parseJson(ko.toJSON(initialData));
//var testTypesPlats = @Html.Raw(Json.Encode(ViewBag.platsTypes));
var viewModel = {
platscuisines: ko.observableArray(dataFromServer),
platstypes : [{ Nom: "Plats", TypeId: 0 },{ Nom: "Crudités", TypeId: 1 },{ Nom: "Tartes Salées", TypeId: 2}],
};
ko.applyBindings(viewModel);
</script>
You can use an attribute defaultValue to set the default value in the Select menu If none option is integrated with this attribute first option is selected by default. You can create an Array of the object where you will store all options to be displayed and any single object is passed in the defaultValue attribute.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
A select box also called drop down box provides an option to list down various options in the form of drop down list. You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.
You would want to write your select like:
<select data-bind="options: viewModel.platstypes,
optionsText:'Nom',
optionsValue: 'TypeId',
value: TypeId">
</select>
This tells Knockout that you want to use the TypeId
property from platstypes
as the value for your options and tells it to read/write the value of the field from the TypeId
property of each item in platscuisines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With