Setting the id attribute with knockoutjs including a prefix
Asked Answered
M

4

80

I'm using KnockoutJS to iterate over an object, like this:

Now this all works. But the problem i have is that it sets the id of the button to just a number. So it looks like this:

<button id="1">Button 1</button>
<button id="3">Button 2</button>
<button id="8">Button 3</button>

So i tried to put a prefix in front of the the 'Id' property, like so:

<div data-bind="foreach:Items">
    <button data-bind="text: Name, attr: {'id': 'myprefix_' + Id}"></button>
</div>

But that doesn't seem to be working. My id gets filled with some Knockout observable function when i do it like that...

So my question is, how can i add a prefix when i specify the id attribute of a field?

Mabelmabelle answered 20/9, 2012 at 8:3 Comment(0)
M
58

If Id is an observable, you must "unwrap" it: 'myprefix_' + Id().

Manly answered 20/9, 2012 at 8:23 Comment(0)
R
75

Actually used this today - to unwrap the observable I had to do:

<button data-bind="attr: { id: 'prefix_' + $index() }"> Send </button>

Hope this helps.

Reuven answered 19/12, 2013 at 1:13 Comment(0)
M
58

If Id is an observable, you must "unwrap" it: 'myprefix_' + Id().

Manly answered 20/9, 2012 at 8:23 Comment(0)
L
30

I think it's best to use the $index for example

<div data-bind="foreach:Items">
    <button data-bind="text: Name, attr: {id: 'myprefix_' + $index() }"></button>
</div>
Lotson answered 14/11, 2013 at 19:32 Comment(1)
I upvoted before I found, at least in my particular case, that I had to use "$index()", not just "$Index".Reinforcement
V
-1

       <img data-bind="event: {click: $root.afficherDetailmembreFamille}" src="ucc/gestion_Famille/images/arbre-fleche-off.png" />

          <label data-bind=" text: nom"></label>
          <label data-bind=" text: prenom, click: $root.afficherDetailmembreFamille"></label>
  <br>

   <div data-bind="attr: {'id': 'DivMembreFamille'+id}" style="margin-left: 40px; display: none;">
Varletry answered 19/4, 2017 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.