How do you get the Ruby on Rails generated id of a form element for reference in JavaScript?

前端 未结 8 846
無奈伤痛
無奈伤痛 2021-02-05 01:01

When using the form_for helper and a text_field call, Ruby on Rails will generate a unique id for the element that it outp

相关标签:
8条回答
  • 2021-02-05 01:48

    You'll want to specify the id yourself. Here generating the id from the object_id of the form guarantees that it won't conflict with another text_field for username in the case of nested forms.

    <%= form_for @user do |f| %>
      <%- id = "username_#{f.object_id}" %>
      <%= f.text_field :username, :id=>id %>
    <% end %>
    
    <%= javascript_tag do %>
      $("##{id}").doSomethingReallyCool();
    <% end %>
    
    0 讨论(0)
  • 2021-02-05 01:52

    Since your Javascript code is placed in a ruby embedded file (.erb) that is being interpreted by the server before being sent to the client browser, you can generated the required JS variable with a ruby snippet like:

    var id='#id_for_'+<%= @user.username %>
    var id='#comment_info_'+<%= n %>
    

    and then use it simply as $(id).doSomethingReallyCool();.

    If you need to control the value of the id generated by the form in first instance, you can do it passing the id in the html hash options:

    f.text_field :username, id:"id_for_#{…}"
    

    If you're using a unobtrusive JS approach, you would like to place the JS code into a partial (.js.erb) and have the controller use it if the user client allows JS. E.g.:

    class FooController < ApplicationController
    
    def foo_doo
      … # some logic
      respond_to do |format|
        format.js # this will render javascript in file “foo_doo.js.erb” if allowed
        format.html { … } # html fallback for unobtrusive javascript
      end
    end
    

    This is the recommended approach nowadays. The problem now is that you need to pass the variables to your JS code. If these variables came from a form, place them in opportune hidden form fields. And then use the render's locals option to have them available by your partial, as in:

    format.js { render 'foo_doo', locals: {n:n} }
    

    If the JS code is updating a template that use some variables, use the same approach:

    var id='#comment_info_'+<%= n %>
    $(id).replaceWith("<%= j (render partial:…, locals: {…}) %>")
    
    0 讨论(0)
提交回复
热议问题