5

I've been using the Cocoon gem to dynamically generate nested fields in rails. I've run into an application where I would like to numerically label the fields generated by cocoon; something like as follows.

Field 1: __________
Field 2: __________
Field 3: __________

I figure I could brute force it by writing my own javascript but is there a built-in feature that would help me to do this?

Many thanks for any guidance.

neanderslob
  • 2,633
  • 6
  • 40
  • 82

2 Answers2

8

You don't necessarily need any JavaScript. Depending on your markup, you might be able to wrap the nested fields and use CSS counters to achieve the numbering. It would also automatically renumber the items if you remove some. Consider this HTML:

<div class="fields">
  <div class="field">Nested fields</div>
  <div class="field">Nested fields</div>
</div>

Together with the following CSS, there will be Field <idx>: before every .field.

.fields {
  reset-counter: idx;
}

.field {
  counter-increment: idx;
}

.field:before {
  content: "Field " counter(idx) ":";
}

You cannot put any HTML directly inside the content's value but other than that you can style the "element" however you want (most notably its position).

Mario Zigliotto
  • 8,315
  • 7
  • 52
  • 71
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52
1

I just had this same issue, basically, you have to update the label of the newly inserted field. I found the answer in this question: Update field inside fields_for with Cocoon and Jquery

What I did was add this in my coffeescript file:

$('#fields').on('cocoon:after-insert', (e, inserted_item) ->
  num = $('.fields').length
  inserted_item.find('.field-label').html('Field #'+num)
 )

You also have to edit the label if you remove any of the fields, but I haven't handled that issue yet.

Community
  • 1
  • 1