+ Start a Discussion

Jquery and components like inputField, outputText, etc

I've started to look into Jquery.  So far in all the VF examples I've seen, the Jquery code references standard HTML tags like divs or html input fields.


When I've tried to reference apex components (inputField, outputText, etc) by their IDs, nothing happens.  Is this because VF is changing the ID values?  For example, when I inspect the firstName inputField using Firebug, I get this in the ID:


<Input id="j_id0:OFLTemplate:j_id11:theBlock:step3:j_id24:firstName" ... >


Set the id param for each parent element (form, pageblock, etc)


then reference the field you want using




You may be able to do it without setting ID's for the parent nodes but it is best practice to set them anyway.


I have not had good luck using the $('#firstName') format but the id$= format works every time for me.



Yes -- when you specify an id attribute for a Visualforce component (standard or custom), Visualforce will mangle your specified id into a fully-qualified, colon-delimited identifier based on the page's component hierarchy (e.g. "j_id0:OFLTemplate:j_id11:theBlock:step3:j_id24:firstName") -- and that's what gets assigned to the DOM id for the associated DOM Element. This is important -- because of it, you can specify a generic id (e.g. id="firstName") for a component within a custom component, and it WON'T yield duplicate DOM ids when you use multiple instances of the outer component in the same page, since the fully qualified ids for each inner component will include a reference to their respective outer component instance.


Note that HTML elements in your Visualforce markup (and their id attributes) will always go through un-mangled. 


Though you can use id suffix fragments (e.g. "j_id24:firstName", e.g. "firstName") to identify a component for Visualforce action rerenders, and you could use those same fragments to find DOM element via jQuery selector predicates, it's better practice to use the fully-qualified ids as much as possible. You can get the fully qualified id via the Visualforce global variable "$Component". Since the mangled id's colon-delimiters will break jQuery's selector syntax, you can either use a javascript RegExp to escape them (via backslash), or just do this:


/* get a jQuery-wrapped Visualforce-generated DOM element via its fully-qualified id; a bit verbose, but no risk of ambiguity here: */



The above will work as long as the above script block is in "proximity" to the "firstName" component. Otherwise, you may find yourself needing to write something more like the following, to help Visualforce figure out exactly which component you're referencing:


/* get a jQuery-wrapped Visualforce-generated DOM element from a script block that resides outside of the "OFLTemplate" element: */