[development] using jquery to access a form element

Jamie Holly hovercrafter at earthlink.net
Wed Jun 23 13:09:39 UTC 2010

You can give your element a name you know won't be used by anything 
else, then access it like this:



If you want the form id that element is in, then:


But the best (and more or less Drupal) way is to assign a class to that 
form element and attach any behaviors through the Drupal JS api:

$form['myelement']=array('#attributes'=>array('class'=>'myclassname'), ...);


Drupal.behaviors.mybehaviourname = function(context) {
   $('.myclassname:not(.myclassname-processed)', context).each(function() {
        // Attach whatever you want to your input element now using $(this)

Put that in a JS file and load it on your page with drupal_add_js and it 
will automatically fire when Drupal does all the other Javascript 
bindings. Also, if you ever change things down the road (say add AJAX) 
and that element gets reloaded, it will automatically reattach the 
behaviors to it.

Jamie Holly

On 6/23/2010 8:45 AM, Lluís Forns wrote:
> I was hoping to find a way to tell my js code which id would have the
> form element.
> I inserted my js code inside the form()
> 2010/6/23 nan wich<nan_wich at bellsouth.net>:
> >  Actually, if the same form is used more than once on a page, you can almost
> >  guarantee that it will *not* have the same name. Take a look at the comments
> >  in "form_clean_id()" concerning its effects on jQuery. I think adding a
> >  class might make this more difficult, unless that code is fully aware of
> >  multiple instances of a form on a page.
> >
> >
> >  Nancy E. Wichmann, PMP
> >
> >  Injustice anywhere is a threat to justice everywhere. -- Dr. Martin L. King,
> >  Jr.
> >
> >  ________________________________
> >  From: Steven Jones
> >
> >  However, you cannot therefore guarantee that the form element will
> >  always have the same ID.
> >
> >  Usually I'd add a class to the item I want to add the behaviour to (in
> >  form alter or theme function), and then attach the javascript using
> >  the Drupal.behaviors technique.
> >
> >  Regards
> >  Steven Jones

More information about the development mailing list