开发者

How to know ids for html fields on Rails 3?

开发者 https://www.devze.com 2023-04-11 20:24 出处:网络
Stage: I am using nested models, supose we have two models: person and car. And here you have new.html.erb page:

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

精彩评论

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

关注公众号