我正在使用Twitter Bootstrap按鈕組以及Knockout。我覺得我忽視了一些非常簡單的事情,但是,在這種情況下,我還沒有能夠獲得checked
綁定的工作。敲除檢查綁定不起作用
我有一個jsFiddle重現這裏的問題:http://jsfiddle.net/n5SBa/。
下面是從小提琴代碼:
HTML
<div class="form-group">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '0'), css: { active: Score() == '0' }">
<input type="radio" name="score" value="0" data-bind="checked: Score" /> 0
</label>
<label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '1'), css: { active: Score() == '1' }">
<input type="radio" name="score" value="1" data-bind="checked: Score" /> 1
</label>
<label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '2'), css: { active: Score() == '2' }">
<input type="radio" name="score" value="2" data-bind="checked: Score" /> 2
</label>
<label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '3'), css: { active: Score() == '3' }">
<input type="radio" name="score" value="3" data-bind="checked: Score" /> 3
</label>
<label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '4'), css: { active: Score() == '4' }">
<input type="radio" name="score" value="4" data-bind="checked: Score" /> 4
</label>
<label class="btn btn-primary" data-bind="click: ClickScore.bind($data, '5'), css: { active: Score() == '5' }">
<input type="radio" name="score" value="5" data-bind="checked: Score" /> 5
</label>
</div>
</div>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
的Javascript
function SurveyViewModel() {
var self = this;
self.Score = ko.observable();
//Events
self.ClickScore = function (score) {
self.Score(score);
};
//Computations
self.RecommendationLabel = ko.computed(function() {
if (self.Score() < 8) {
return "Some question?";
} else {
return "Some other question?";
}
});
self.DOMSelectedScore = ko.computed(function() {
if ($('input[name=score]:checked').val()) {
return $('input[name=score]:checked').val();
} else {
return 'no value!';
}
});
};
var surveyViewModel = new SurveyViewModel();
ko.applyBindings(surveyViewModel);
在這個例子中,我無法獲得實際的單選按鈕在DOM中選中,以便它可以正確提交到我的表單中。
我其實有我的代碼設置傳遞字符串,這是我的一個錯字。即使在你連接的小提琴中,問題仍然存在(DOM選定值仍未定義) –
我打開控制檯並運行$('input [name = score]:checked')',並返回正確的項目。 –
我給你+1,因爲你的回答肯定有幫助。但是,我只是添加了自己的答案,因爲看起來問題比我想象的要複雜得多。 –