htmlhtml-selectjavascript-databinding

HTML Select Form Variable Default Value


I am trying to set a default value for a HTML select form. I've read the posts on setting a constant default value for a select form. However, I want the default value to be the variable shirt.Color, which is either Small, Medium, or Large depending on the shirt.

For example, if shirt.Color is Small, I want the select form to have Small selected; if shirt.Color is Medium, I want the select form to have Medium selected; if shirt.Color is Large, I want the select form to have Large selected.

I know how to set default values for text boxes using data-binding. I set the default shirt color using the following:

<div class="form-group">
    <label class="control-label col-sm-2">Shirt Color</label>
    <input type="text" name="color" data-bind="valueUpdate: 'input', value:shirt.Color" class="form-control" required />
</div>

Is there something similarly simple I could do for a select form? I'd rather not manually code each case for Small, Medium, and Large.

I have tried doing

<div class="form-group">
    <label class="col-sm-2 control-label col-sm-2">Shirt Size:</label>
    <select required name="type" data-bind="type: 'input', value: shirt.Size">
        <option value="s">Small</option>
        <option value="m">Medium</option>
        <option value="l">Large</option>
    </select>
</div>

However, this always defaults to the first option, Small.


Solution

  • You can use a kendoDropDownList for this.

    <div data-bind="kendoDropDownList: { data: shirtSizes, dataTextField: 'SizeName', dataValueField: 'SizeId', value: shirt.Size } />

    Where shirtColors is an array containing ColorName and ColorId fields.

    var shirtSizess = [ { SizeId: 's', SizeName: 'Small' }, { SizeId: 'm', SizeName: 'Medium' }, { SizeId: 'l', SizeName: 'Large' } ];