如何获得下拉列表的选定值?

时间:2014-07-04 14:47:03

标签: jquery asp.net-mvc asp.net-mvc-4 knockout.js knockout-2.0

我正在尝试获取所选的下拉值,但我的代码不起作用。

此处JsFiddle

查看

<select style="height: 26px;" data-bind="options: StateTitle, 
        event: { change: ddlState }, optionsText: 'StateText', 
        optionsValue: 'StateId', value: selectedState, 
        optionsCaption: 'Choose State.....'"></select>

视图模型

function AppViewModel() {
    var self = this;
   self.StateTitle = ko.observableArray([]);
self.selectedState = ko.observable();
    var data = {
        StateId:1,
        StateText:'Demo'

    }
    self.StateTitle(data);

      self.ddlState = function (newValue) {
        alert("State Id " + ko.toJSON(newValue.StateId));
    }
}

  ko.applyBindings(new AppViewModel());

4 个答案:

答案 0 :(得分:2)

我认为你的变化事件使你复杂化了。您可以只引用您拥有的selectedState selectStateId<select style="height: 26px;" data-bind="options: StateTitle, optionsText: 'StateText', optionsValue: 'StateId', value: selectedState, optionsCaption: 'Choose State.....'"> </select> <p data-bind="text: selectedState"></p> 的值传递给function AppViewModel() { var self = this; self.StateTitle = ko.observableArray([{ 'StateId': 1, 'StateText': 'Demo' }, { 'StateId': 2, 'StateText': 'Another' }]); self.selectedState = ko.observable(); } ko.applyBindings(new AppViewModel());

Sample JSFiddle

<强>标记:

self.selectedState.subscribe(function(item) {
    alert('Selected State Id:' + item);
});   

<强>敲除

{{1}}

要创建警报,只需订阅observable:

Updated Fiddle

{{1}}

答案 1 :(得分:0)

function AppViewModel() {
    var self = this;
   self.StateTitle = ko.observableArray();
self.selectedState = ko.observable();
    var data = {
        StateId:1,
        StateText:'Demo'

    }
    self.StateTitle.push(data);

      self.ddlState = function () {
        alert("State Id " + self.selectedState().StateId);
    }
}

答案 2 :(得分:0)

您需要像这样订阅selectedState

self.selectedState.subscribe(function (data) {
        console.log(data)
    });

现在,当下拉选项发生变化时,这将跟踪StateId

UPDATED FIDDLE

答案 3 :(得分:0)

您只需添加一点支票http://jsfiddle.net/29u4X/

self.selectedState.subscribe(function(newValue) {
    //check if nothing is been selected
    if (typeof (newValue) === 'undefined' || newValue === '') {
        return;
    }
    //Do want ever you want to do
    alert(newValue);
});