0

I want to bind my text input value

<input type="text" id="2" data-bind="value :  ??whatToWriteHere??    ">

to the second object's name property in the following observable object ( where input.id == object.id )

myObject = {
    myArray : [ { id:1, name:'one' },{ id:2, name:'two' },{ id:3, name:'three' } ]
},
myObservableObject = ko.observable(myObject);

With what expression I should replace ??whatToWriteHere??

Edited: actually the array is not necesserily be inside another object

 myArray : [ { id:1, name:'one' },{ id:2, name:'two' },{ id:3, name:'three' } ]
 myObservableArray = ko.observableArray(myArray);

2 Answers 2

2

I've a solution based on ko.mapping plugin and a custom binding created for your purpose.

You can see a working fiddle here:

http://jsfiddle.net/ingro/MhdZp/

The whole idea is to map your observableArray and then retrieve the one tied to your input id with the mappedIndexOf function of the mapping plugin.

Sign up to request clarification or add additional context in comments.

Comments

0

It depends what the data context of the input is. If the objects within myObservableArray are being bound to templated input elements, then the binding would be "value: name". Are you using a foreach? Or is there only one input element here which you explicitly want to bind to that second array element, where myObservableArray is just declared somewhere in the page? If so, it'd be "value: myObservableArray()[1].name".

3 Comments

I have like 10(this number can change dynamically, independent of myArray) input elements, and myArray may have 0-10 items in it(this number is also dynamic). I am not using foreach, even if I have used it would not depend on my array. I want to match my input elements with the items in the array based on input elements id attribute and array items id property.
Are the inputs and their IDs being generated server side? If so can you not use whatever view logic you use to generate id="2" to plug that 2 (minus 1 to get the array index) into the binding? E.g. "value: myObservableArray()[2 - 1] where 2 is generated with whatever server side view syntax you're using. Do I understand it correctly?
Actually the case is like this. Suppose I have a list all brands of cars available in a store(say 10), and there is an input element for each brand whose id s are equal to their matching brand id. And I have customer who has a few cars (say 3) and I am trying to write the payment of the customer inside these input elements. so the id s are brand ids. I use web services to fetch data and dynamically build page using JQUery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.