HTML 5验证无法在Firefox中使用Knockout选项绑定

时间:2014-11-18 22:47:50

标签: html5 validation firefox knockout.js

我试图强制用户在下拉菜单中选择一个选项,由Knockout填充。我正在使用HTML5“必需”验证属性,它在Chrome 38和Opera 25中运行良好,但在Firefox 33中失败。

这是我的HTML:

<form id="theForm" class="form-horizontal form-validate" action="" method="post">
    <div class="control-group">
        <label class="control-label">To</label>
        <div class="controls">
            <select required data-bind="options: listRecipients,
                                    optionsCaption: 'Choose...', 
                                   optionsText: 'name',
                                   value: selectedRecipient"></select>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit Changes</button>
</form>

以及相应的JavaScript:

$(document).ready(function () {
    function AppViewModel() {
        // KO model
        self.listRecipients = ko.observableArray([{
            name: 'foo',
            id: '1'
        }, {
            name: 'bar',
            id: '2'
        }]);
        self.selectedRecipient = ko.observable();
    }

    // Activates knockout.js
    var appViewModel = new AppViewModel();
    ko.applyBindings(appViewModel);
});

对应jsFiddle

使用带有Knockout“选项”的jQuery验证看起来相当复杂,我找不到很多关于使用“选项”使用敲除验证的文档......不知道为什么它不能用于FF?

1 个答案:

答案 0 :(得分:0)

Knockout sports databind optionsValue如果它是id,你想存储在可观察的selectedRecipient中,只需添加optionsValue:'id'

<form id="theForm" class="form-horizontal form-validate" action="" method="post">
    <div class="control-group">
        <label class="control-label">To</label>
        <div class="controls">
            <select required data-bind="options: listRecipients,
                                    optionsCaption: 'Choose...', 
                                   optionsValue: 'id',   
                                   optionsText: 'name',
                                   value: selectedRecipient"></select>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit Changes</button>
</form>

对应jsFiddle.