2
votes

I am currently working on some Knockout js templating stuff. My requirement is I need to set the name of a field (input) with a combination of string and the index value of the row. For example "xxx3".

I tried two options.

'xxx' + ko.utils.arrayIndexOf(viewModel.mycollection, $data)

and

'xxx' + $index

The first option always gives '-1' for my index value and the second option doesnt work becasue seems like I can only use the $index value without any string concatenation.

Could someone let me know if I can concatenate a string value to $index value in knockout so that I can set that to the name property of an input field.

The final result I want should be like this.

<input class="text-box single-line" data-val="true" 
   data-val-required="The XXX field is required." id="XXX" type="text" name="XXX3">

Here is how my template looks like.

<table id ="editorRows" class="table">
        <tbody data-bind='template: {name: "rowTemplate", foreach: Rules }'></tbody>
    </table>

    <script id="rowTemplate" type="text/html">
        <tr data-bind="attr: { id: RuleKey }">
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" data-val="true" data-val-required="The Name field is required." id="Name" type="text" data-bind="value: Name, attr: {name : 'Rules[' + $index + '].Name'}" />
                    <span class="field-validation-valid" data-bind="attr : { 'data-valmsg-for': 'Rules[' + $index + '].Name'}" data-valmsg-replace="true"></span>
                </div>
            </td>
</tr>
</script>
1
Post your template code. - Yograj Gupta
$index only works in the context of a foreach binding. Are you using it in the right places? - Jeff Mercado
Why you are doing attr: {name : 'Rules[' + $index + '].Name' it. Is `attr : {name : Name } is not working or you want name like Rules[0].Name. - Yograj Gupta

1 Answers

3
votes

$index is an observable, so you would need to call it to retrieve the value. So assuming you are trying to set the values of the attributes to literally Rule[0].Name, you'd do this:

<input class="text-box single-line" data-val="true" data-val-required="The Name field is required." id="Name" type="text"
       data-bind="value: Name, attr: {name : 'Rules[' + $index() + '].Name'}" />
<span class="field-validation-valid" data-valmsg-replace="true"
      data-bind="attr : { 'data-valmsg-for': 'Rules[' + $index() + '].Name'}"></span>