如何使用14.04
optionsCaption
中删除select tag ?
我的knockout JS
就像:
select tag
它将<select data-bind="options: categories, optionsText: 'type', optionsCaption: 'Select Any Ticket type', value: chosenCategory, disable: showReservationDetails, event: {change: calRemainingTickets}"></select>
显示为第一个Select Any Ticket
。 option
的{{1}}我要删除on change
。
select tag
来自Select Ant Ticket option
remove
我们如何required option
先谢谢你。
答案 0 :(得分:5)
您可以将optionsCaption绑定到observable,并将observable的值设置为undefined。我修改了Joe的代码来执行此操作。
var vm = function () {
this.optionsCaption = ko.observable('Select any');
this.categories = ko.observableArray([ {type: 'Type 1' }, { type: 'Type 2' }]);
this.chosenCategory = ko.observable('Select Any Ticket type');
this.showReservationDetails = ko.observable(false);
this.calRemainingTickets = function () {
this.optionsCaption(undefined);
}.bind(this);
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<select data-bind="options: categories, optionsCaption: optionsCaption, optionsText: 'type', value: chosenCategory, disable: showReservationDetails, event: {change: calRemainingTickets}"></select>
答案 1 :(得分:0)
[示例] http://jsfiddle.net/cg988b4n/
它有点 smoke-and-mirror-y 。但它的工作原理是不使用optionsCaption
。 change事件会在第一次更改时删除该默认选项。您的逻辑typeId === -1
必须更改为使用符合您逻辑的任何内容。
我的观点模型
var vm = function () {
this.categories = ko.observableArray([{ type: 'Select Any Ticket type', typeId: -1 }, {type: 'Type 1' }, { type: 'Type 2' }]);
this.chosenCategory = ko.observable('Select Any Ticket type');
this.showReservationDetails = ko.observable(false);
this.calRemainingTickets = function () {
if (this.categories()[0].typeId === -1) {
this.categories.shift();
}
}.bind(this);
}
ko.applyBindings(new vm());
答案 2 :(得分:0)
Knockout会在applyBindings
上插入标题选项,但您可以在以后删除它而不会影响您的视图模型或KO抱怨。像Joe这样的解决方案将占位符选项插入到viewmodel中会起作用,但我个人更喜欢将其保留在我的数据之外,而是执行类似这样的操作:
vm.calRemainingTickets = function (data, event) {
var el = event.target.options[0];
el.value || el.remove();
// whatever else needs doing
};
这样做是删除绑定选择元素的第一个选项子元素,如果它有一个假的选项值,你的optionsCaption
会。您也可以检查text === 'Select Any Ticket type'
或设置“已删除第一个元素”标记。
答案 3 :(得分:0)
你可以这样恢复:
var vm = function () {
this.optionsCaption = ko.observable('Select any');
this.categories = ko.observableArray([ {type: 'Type 1' }, { type: 'Type 2' }]);
this.chosenCategory = ko.observable('Select Any Ticket type');
this.showReservationDetails = ko.observable(false);
this.calRemainingTickets = function () {
this.optionsCaption(undefined);
}.bind(this);
this.putItBack = function() {
this.optionsCaption('Select Any');
}
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<select data-bind="options: categories, optionsCaption: optionsCaption, optionsText: 'type', value: chosenCategory, disable: showReservationDetails, event: {change: calRemainingTickets}"></select>
<a href="#" data-bind="click:putItBack">Put It Back</a>