【发布时间】:2013-12-27 07:21:57
【问题描述】:
我正在使用 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 中选择实际的单选按钮,以便它可以在我的表单中正确提交。
【问题讨论】:
标签: javascript twitter-bootstrap knockout.js