开发者

How to know ids for html fields on Rails 3?

Stage: I am using nested models, supose we have two models: person and car. And here you have new.html.erb page:

<%= form_for(@person do |f| %>
  ...
  <%= f.fields_for :cars do |car| %>
    <div class="field">
      <%= car.label :color %><br />
      <%= car.text_field :color, :maxlength => 7 %>
    </div>
  <% end %>
  ...
<% end %>

This code will generate for each car:

<form ...>
  ...
  <div class="field">
    <label for="person_cars_attributes_0_color">Car color</label><br />
    <input id="person_cars_attributes_0_color" 
           name="person[cars_attributes][0][color]" 
           size="7" type="text" />
  </div>
  ...
</form>

Now suppose we need to put some javascript code for each input field, to generate something like this:

    <script type="text/javascript">
      $(document).ready( function() { $('#person_cars_attributes_0_color').mycolorpicker(); });
    </script>
    <input id="person_cars_attributes_0_color" 
           name="person[cars_attri开发者_运维知识库butes][0][color]" 
           size="7" type="text" />

Notice, we need in javascript code input field id (in this example person_cars_attributes_0_color).

Problem: How can we get this id value for each html field generated?

Thank you very much for your help. Please feel free to ask me anything if you need more details.


How about assigning the field in question an ID or class that you determine before hand?

new.html.erb:

<%= form_for(@person do |f| %>
  ...
  <%= f.fields_for :cars do |car| %>
    <div class="field">
      <%= car.label :color %><br />
      <%= car.text_field :color, :maxlength => 7, :class => 'colorpicker' %>
    </div>
  <% end %>
  ...
<% end %>

JavaScript:

$(document).ready(function() {
  $('.colorpicker').mycolorpicker();
});


I would highly recommend checking out the nested_form gem by Ryan Bates. I think it will take care of everything that you are looking to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜