Search code examples
javascriptknockout.jsbreeze

Knockout Bindings using Key value pair Inside foreach


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 inside foreach binding. What I want to do, is to Display the 'Name' attribute into the text box and after retrieving the corresponding 'Id' attribute from my database.

"operator"[successfully accessed from breeze] is a attribute defined in database which have int value 1, hence my text box must display the corresponding value from "operators" [defined in my javascript file] i.e.,"Subtraction" for one record

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

My HTML bindings

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

         <div>
        <label>operator :</label>
         <input type="text" data-bind="text:operators.name, 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.

I know I am not correct but I need to find some way to figure out the above issue.

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.


Solution

  • Without seeing the rest of the code, the biggest issue with your code is using a with binding instead of a foreach. Foreach is used to iterate, with is used to change the context.

    <div data-bind="foreach: jobs">
          <div>
            <label>FirstNumber :</label>
            <input data-bind="value: first_no" />
        </div>
    
             <div>
            <label>operator :</label>
             <input type="text" data-bind="text:operators.name, 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>