ashishraaj
ashishraaj

Reputation: 761

Knockout Bindings using Key value pair

I am working on knockout with BreezeJs for retrieving and storing data from my local database. The problem I am facing here is the key value binding in menu. What I want to do is to Display and select the 'Name' attribute from the select menu and store the corresponding 'Id' attribute into my database.

Till now I am trying like

var operators = [
{id: 0, name: 'addition'},
{id: 1, name: 'subtraction'},
{id: 2, name: 'division'},
{id: 3, name: 'multiplication'}
   ];

// my html bindings

<select data-bind="options: $root.operators , optionText: 'name', optionvalue: 'Id', value: operator"/>

// here 'operator' is the colomnName from database in which I am trying to store this thing in integer format.

But as per my code its showing output as

[object object]

How can I solve this issue for displaying and selecting the 'name' attribute [varchar] from the select menu and store the corresponding 'id' attribute [int] to my database.

//@TSV

The html bindings

 <div data-bind="with: jobs">
      <div>
        <label>FirstNumber :</label>
        <input data-bind="value: first_no" />
    </div>

         <div>
        <label>operator :</label>
         <select data-bind="options: $root.operators , optionsText: 'name', optionsValue: 'id', value: $root.operator"/>
    </div>
     <div>
        <label>Second Number:</label>
        <input data-bind="value: second_no" />
    </div><div>
        <label>Result :</label>
        <input data-bind="value: result" />
    </div></div>

// these(result,second_no,operator,first_no) are the column names in my database and 'jobs' is an observableArray.

Note : I am using breezeJS to get & store data from database that's why I mentioned a tag of it, though the above problem is of knockout rather than breeze.

Upvotes: 1

Views: 1118

Answers (1)

TSV
TSV

Reputation: 7641

This code works for me:

var operators = [
{id: 0, name: 'addition'},
{id: 1, name: 'subtraction'},
{id: 2, name: 'division'},
{id: 3, name: 'multiplication'}
   ];

ko.applyBindings({ operators: operators, operator: ko.observable(2) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>

<select data-bind="options: $root.operators, optionsText: 'name', optionsValue: 'id', value: 
$root.operator"/>

I've patched following issues in your code: inserted comma after "division'}", corrected "optionsText" and "optionsValue" params, optionsValue should be 'id'.

Upvotes: 3

Related Questions