2016-04-14 61 views
3

获取文本值我有各种图像类型下拉:从淘汰赛下拉

<select class="form-control" data-bind="options: imageCategoryList, value: 'Category', optionsCaption: --Select Category--, optionsText: &#39;Category&#39;, optionsValue: 'Category', event: {change: GetImages}" id="Category" name="Category"></select>

在我的JavaScript,我试图让无论是在下拉列表中选择的文本值,但我不知道该怎么做。在我看来,我有

var img = self.imageCategoryList().Text 

但只返回“未定义”。我如何获得选定的文本值?

提前致谢!

回答

1

我想这可能是你正试图在这里完成什么...

工作小提琴:http://jsfiddle.net/bPP5Q/33/

的观点...

<select class="form-control" data-bind=" 
    options: imageCategoryList, 
    value: selectedCategory, 
    optionsCaption: '--Select Category--', 
    optionsText: function(item){ return item.Category }, 
    event: {change: getImages}" 
id="Category" name="Category"></select> 

和视图模型...

jQuery(function ($) { 
    // this runs after the window loads 
    var ViewModel = function (data) { 
    var self = this; 

    self.imageCategoryList = ko.observableArray([ 
     { 
     Category: 'A', 
     Text: 'CategoryA' 
     }, 
     { 
     Category: 'B', 
     Text: 'CategoryB' 
     }, 
     { 
     Category: 'C', 
     Text: 'CategoryC' 
     } 
    ]); 

    self.selectedCategory = ko.observable(); 

    self.selectedCategory.subscribe(function(newValue) { 
     console.log(newValue.Text); 
    }); 

    self.getImages = function(){}; 
    } 


    var vm = new ViewModel(); 

    ko.applyBindings(vm); 

}); 
+0

我无法对你表示赞赏(我没有足够的声望),但非常感谢! – heztet

+0

当我尝试用'var txt = newValue.Text'来代替'console.log(newValue.Text);'时,我得到了一个未定义的txt错误。如何记录selectedCategory的文本以在其他地方使用? – heztet

+1

它可能只是您变量的范围。尝试将其分配给self.newTextValue而不是txt,并查看是否可以在其他地方访问它。 –

2

您应该将您选择的选项绑定到observable。 洙在你的模型创建:

self.selectedCategory = ko.observable(); 

,并在您选择

<select class="form-control" data-bind="options: imageCategoryList, value: selectedCategory, optionsCaption: --Select Category--, optionsText: 'Category', optionsValue: 'Category', event: {change: GetImages}" id="Category" name="Category"></select> 

而且在你的JavaScript可以访问它像

var img = modelObject.selectedCategory(); 

这不是测试,但它是一个开始。

+0

什么是'modelObject'?我收到一个未定义的错误。 – heztet