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

前端 未结 8 890
無奈伤痛
無奈伤痛 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:43

    I assume that there are multiple form_for in the page and each has it's own submit button. I think this is how I would do this:

    Have a hidden field in the the form_for and set it's value to the id of the input field. Here I've chosen input_#{n} as the id of the input field. Of course I'll define the id for each input.

    <%= form_for @user do |f| %>
      <%= f.text_field :username, id: "input_#{n}" %>
      <%= hidden_field_tag 'user[input_id]', value: "input_#{n}" %>
      <%= f.submit %>
    <% end %>   
    

    Then on submit I can get the id the form input in my params params[:user][:input_id] which I can pass to the js.erb using the locals.

    Hope this helps :)

提交回复
热议问题