HTML Select Form Variable Default Value

2.1k views Asked by At

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.

2

There are 2 answers

0
Emmett Lin On BEST ANSWER

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' } ];

1
Vance On

Your question is somewhat vague so Im assuming that what you want to do is to set a default value for your select list. To do it, just add "selected" inside the option tag that contains the value that you want to be selected by default. Here's an example:

<option value="s">Small</option> <option value="m" selected>Medium</option> <option value="l">Large</option> The default value for your select list is now "m".