下拉列表将接受一个不属于列表的值,也可以在Knockout

时间:2017-04-21 13:34:22

标签: select knockout.js drop-down-menu

输入电子邮件地址时,用户必须选择电子邮件  来自预定义列表的域(例如,gmail.com; outlook.com; hotmail.com)。

“域名”下拉列表也会接受不属于列表的值。

我应该同时选择和输入功能。

HTML:

 <!-- Mulitple array of emails   -->
    <div>
       <table class="table table-bordered">
          <tbody data-bind='foreach: billDeliveryEmails'>
             <tr>
                <td><input class='required' data-bind='value: userName' /></td>
                <td><select data-bind="options: $root.availableEmailDomains(), value: domainName, optionsText: 'domainName', optionsValue: 'domainName'"></select></td>
                <td><a  data-bind="click:'removeDeliveryEmailAddress'">Delete</a></td>
             </tr>
          </tbody>
       </table>
       <a class="atm-bloque-link" data-bind="click:'addDeliveryEmailAddress'">Agregue otra direccion de email</a>
    </div>

VM:

//域类

 function Domain(domainName) {
            var self = this;
            self.domainName = domainName;
           }

    billDeliveryEmails : [],
availableEmailDomains : ko.observableArray([
        new Domain("hotmail.com"),
        new Domain("yahoo.com")
    ])


     addDeliveryEmailAddress: function ($element, data, context, bindingContext, event) {

            bindingContext.$root.billDeliveryEmails.push({
                userName: "",
                domainName: this.viewModel.get('availableEmailDomains')[0]
            });

            event.preventDefault();
        },

        removeDeliveryEmailAddress: function ($element, data, context, bindingContext, event) {

            bindingContext.$root.billDeliveryEmails.splice(0, 1)
            event.preventDefault();
        }

1 个答案:

答案 0 :(得分:0)

根据评论中的链接,以下是一个示例:

function Domain(domainName) {
  var self = this;
  self.domainName = domainName;
}
           
var vm = function () {
	var self = this;
	self.browser = ko.observable();
  self.browserList = ko.observableArray([
  	new Domain('yahoo.com'),
    new Domain('hotmail.com')
  ])
}();

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" data-bind="value: browser" /></label>
<datalist id="browsers" data-bind="foreach: browserList">
  <option data-bind="text: domainName">
</datalist>

<br />
Your browser is: <span data-bind="text: browser"></span>

可观察数组用于填充列表,常规可观察数据跟踪所选值。