Princa
Princa

Reputation: 447

Knockout.js foreach not working for second or more elements

Trying to bind an array with a table, if I have this:

<table data-bind="foreach: Applicants, visible: Applicants().length > 0">
        <tr>
        <td>
        <p data-bind="text:FirstName() + ' ' + LastName()" />
        <img data-bind="attr:{src: URL}" width="100px" height="100px" alt="test" /></td>
        </tr>
</table>

the img tag won't be generated, just omit from the display.

Have to have another <td> wrap <img> to display it. Why?


Ok, @Stokedout is right, after trying with </p> instead of using closed tag <p .... />, it works. So if the tag could have value but is closed without any value then knockout won't work for the rest of tags..

Example:

Will work: -- Both first name and last name will display.

      <p data-bind="text: FirstName"></p>
      <p data-bind="text: LastName"></p>

Will NOT work: -- ONLY first name will display

      <p data-bind="text: FirstName"/>
      <p data-bind="text: LastName"/>

I AM NOT SURE WHY!

Upvotes: 1

Views: 630

Answers (2)

Michael Best
Michael Best

Reputation: 16688

It's because the <p> element must have full element syntax.

<p data-bind="text:FirstName() + ' ' + LastName()"></p>

Without it, the HTML becomes:

<p data-bind="text:...">
    <img ... />
</p>

So the img becomes the contents of the p element and gets overwritten by the text binding.

Upvotes: 2

phnkha
phnkha

Reputation: 7872

When you write:

<p data-bind="text:FirstName() + ' ' + LastName()" />
<img data-bind="attr:{src: URL}" width="100px" height="100px" alt="test" />

Without a closing tag, the img will be treated as the content the paragraph. For self-closed P element, the browser can infer that the paragraph has ended by the start of the next paragraph.

When you bind using this:

data-bind="text:FirstName() + ' ' + LastName()" 

KO will try to set text to your P element and it clear the previous content.

Solution is very simple, just add a closing tag:

<p data-bind="text:FirstName() + ' ' + LastName()"></p>
<img data-bind="attr:{src: URL}" width="100px" height="100px" alt="test" />

Upvotes: 3

Related Questions