I am using the attr binding to set the name and value of an input tag. The problem is I don't know the binding to use for the value. I have tried text and value so far but with no luck. My code looks like this:
<div data-bind="foreach: witnesses">
<input data-bind="attr: { name: 'firstName', text: firstName }"/>
</div>
I am hoping that this will render as:
<input name='firstName value=`enter code here`'Joe'>
or even
<input name='firstName'>Jo`enter code here`e</input>
How to achieve this? Also, how do I get the index of the current iteration of the foreach loop, since I need to add this to my name..
Mark
Try the following:
<div data-bind="foreach: witnesses">
<input data-bind="attr: { name: 'firstName' + $index()}, value: firstName"/>
</div>
Here I'm concatenating the foreach index (zero-based) into the name of the input element. It's not actually necessary but since you mentioned it I assume you need it.
It would probably make more sense to use a css class if you're looking to identify all of those inputs.
an instant solution . by the way you forgot the type attribute . you should set it.
<div data-bind="foreach: witnesses">
<input type="text" name='firstName' data-bind="value: 'enter code here ' + firstName"/>
</div>
and as others mentioned $index
gives you index of current item in the loop.