# How to get form element id's?

**URL:** <https://www.ruby-forum.com/t/how-to-get-form-element-ids/170760>\
**Category:** Rails\
**Created:** [June 22, 2009, 2:40pm UTC](https://www.ruby-forum.com/t/how-to-get-form-element-ids/170760 "2009-06-22T14:40:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jdunneuk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/35a633/32.png) [@jdunneuk](https://www.ruby-forum.com/u/jdunneuk)\
**Post date:** [June 22, 2009, 2:40pm UTC](https://www.ruby-forum.com/t/how-to-get-form-element-ids/170760/1 "2009-06-22T14:40:26Z")

</div>

Hi there,

I’m going to start with an example:

\<% form\_for(@post) do |f| %\>

\<%= f.label :title %\>  
 \<%= f.text\_field :title %\>

\<% end %\>

Generates:

Title

Is there any way to get the input id as a string out of the form (f)  
object? The example is quite simple, but if there are nested forms there  
are id’s like thread\_posts\_attributes\_0\_title and I need that id to  
modify the value with JavaScript. Hope there’s a solution.

Thanks!

---

<div class="post-metadata">

**Author:** ![jdunneuk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/35a633/32.png) [@jdunneuk](https://www.ruby-forum.com/u/jdunneuk)\
**Post date:** [June 22, 2009, 3:06pm UTC](https://www.ruby-forum.com/t/how-to-get-form-element-ids/170760/2 "2009-06-22T15:06:13Z")

</div>

You could just specify the id yourself, rather than trying to  
read/replicate the auto-generated one, is that an option? That way you  
know for sure what it’s going to be called, which will make it easier to  
refer to in your JS.

If so then use the :id option and make sure you give it a unique id,  
like “post\_#{post.id}\_name” or something.

---

<div class="post-metadata">

**Author:** ![jdunneuk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/35a633/32.png) [@jdunneuk](https://www.ruby-forum.com/u/jdunneuk)\
**Post date:** [June 22, 2009, 3:41pm UTC](https://www.ruby-forum.com/t/how-to-get-form-element-ids/170760/3 "2009-06-22T15:41:46Z")

</div>

Max W. wrote:

> You could just specify the id yourself, rather than trying to  
> read/replicate the auto-generated one, is that an option? That way you  
> know for sure what it’s going to be called, which will make it easier to  
> refer to in your JS.
> 
> If so then use the :id option and make sure you give it a unique id,  
> like “post\_#{post.id}\_name” or something.

That is indeed an option. Thank you very much!
