13

I have an observable array:

var myObservableArray = ko.observableArray([
    { name: "Car", price: "9999" },
    { name: "Shoes", price: "20" },
    { name: "Paper", price: "1" }
]);

I'm trying to access the price of the first item in the array.

<div data-bind="text: myObservableArray()[0]"></div>

Displays:

[object Object]

I've tried:

<div data-bind="text: myObservableArray()[0].price"></div>

But that just returns a null.

What's the correct syntax for doing this?

Edit: Fixed a copy and paste error pointed out below.

1
  • That's how you do it. If it's not working, you have some other issue with your code. Commented Apr 18, 2013 at 18:31

3 Answers 3

7

Other than using the wrong property name, developerexampledata instead of myObservableArray, your code is just fine.

Here is a working fiddle

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

1 Comment

Yeah that was a copy and paste error when I made the question, my bad. I appreciate the fiddle though; at least I know I've got the syntax right and my problem lay elsewhere. I'll accept your answer and dig in a bit more to figure out where else I might be going wrong.
1

This could simply be down to you trying to access the first item of an array before the array has been populated.

Wrap your data-bind control with a simple if statement to check first:

<!-- ko if: (myObservableArray().length > 0) -->
    <div data-bind="text: myObservableArray()[0].price"></div>
<!-- /ko -->

Comments

0

wrong way.....

self.getvaluefrom = function (a ,b)

try catch return a valid value then add data-bind="text:getvaluefrom(a,b) if the item is not in the array you'll get a ko error....

ko html displays only a static valid entry of an array....

3 Comments

Also if you want to populate the array .... use var myarrayonload = function() alert("i loaded") its a private function .... then load what ever you want into the array....
var onload = ko.computed(function()
no loops needed..... click: function === self.onclick = function(data,event) now use the var a = self.arrayentery.indexOf(data);

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.