webGuy
webGuy

Reputation: 163

knockout JS option data-bind multiple values

I would like to do add multiple values to the data-tokens attribute:

<option data-bind="text: customer_display_name, value: customer_id, attr: {'data-tokens': customer_first_name, customer_last_name}"></option>

Unfortunately this wont work, only the data-tokens "customer_first_name" works and the "customer_last_name" dont. How can I add multiple valus?

EDIT: I would also like to do the same inside an options binding:

<select class="form-control selectpicker" data-live-search="true"
    data-bind="options: $parent.customers, optionsText: 'customer_display_name', optionsValue: 'customer_id', value: customer_id,
    event: {change: $parent.changeWorkCustomer}, attr: {'data-tokens': [$parent.customer_first_name, $parent.customer_last_name]}, css: { customer_fav: $parent.fav > 0 }">

It does not work like this. Thank you for your help.

Upvotes: 0

Views: 896

Answers (2)

Akrion
Akrion

Reputation: 18515

You can do this also by wrapping them in an array and then unwrap by calling for their value:

data-bind="attr: {'data-tokens': [attr1(), attr2()]}

ko will figure out what needs to be done and output multiple values:

function MyViewModel() {
  this.attr1 = ko.observable('test1')
  this.attr2 = ko.observable('test2')
}
ko.applyBindings(new MyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="attr: {'data-tokens': [attr1(), attr2()]}">Testing!</div>
<input type="text" data-bind="value: [attr1(), attr2()]" />

If you do inspect element on the Testing! you will see that the result is:

data-tokens="test1,test2"

Upvotes: 1

Ray
Ray

Reputation: 3959

You mean you want the values of both variables, with a comma in between?

Try this:

attr: {'data-tokens': (customer_first_name + ', ' + customer_last_name)}

Upvotes: 0

Related Questions