2016-04-14 62 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