设置下拉列表的默认值

时间:2016-07-11 16:58:15

标签: javascript jquery html knockout.js drop-down-menu

我试图为我下载的下拉菜单设置默认值。所有12个月的下拉功能。它是动态填充的。但是,我尝试将其设置为默认下拉值是当前月份。我使用的是KnockoutJS

以下代码是我如何向dropdown html代码发送信息。

            self.setMonthData = (data: any) => {
            var len = data.List.length,
                i;

            var monthData = [];

            for (i = 0; i < len; i++) {
                self.monthData.push(
                    {
                        name: data.List[i].month,
                        month: data.List[i].monthNumber
                    }
                )
            }
        }

HTML代码:

                <select id="monthSelect" class="select select2" style="margin: 10px;"
                    data-bind="options: monthData,
                                optionsText: 'name',
                                optionsValue: 'month'">
                <option></option>
            </select>

此代码是页面加载下拉列表的方式。

        $(function () {
        ko.applyBindings(viewModel);
        getGridData(initialMonth, initialYear);
        viewModel.load();

        $("#monthSelect").on('change', function () {
            var month = $('#monthSelect').find("option:selected").val();
            var year = $('#yearSelect').find("option:selected").val();
            viewModel.loadChangesData(month, year);
            getGridData(month, year);
        });

        $("#yearSelect").on('change', function () {
            var month = $('#monthSelect').find("option:selected").val();
            var year = $('#yearSelect').find("option:selected").val();
            viewModel.loadChangesData(month, year);
            getGridData(month, year);
        });
    });

1 个答案:

答案 0 :(得分:2)

The reason your code isnt working is because you need to set the value of the select. By setting the value binding in a select control you are telling your ViewModel which observable you want to hold the currently selected option in your select dropdown.

As an aside, if you are using an array you probably dont need a month number as it is implicit in the position of each month in the monthData array. i.e. Jan is stored at index 0, Feb at index 1, etc.

var vm = function() {
  var self = this;
  self.months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec'
  ];
  self.selectedMonth = ko.observable(self.months[new Date().getMonth()]);
}

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Defaulted to current month:
<select data-bind="options: months, value: selectedMonth"></select>
<br/>
<br/>
Selected Month: <b data-bind="text: selectedMonth"></b>