+ Start a Discussion
ministe_2003ministe_2003 

JQuery doesn't work on elements not rendered at load time

Hi,

If you have an element conditionally not rendered at load time, how can I attach a jQuery function to it?  I have a button which is hidden at load time but renders once all fields have been filled out.  I have attached a jQuery function to listen for the button click and perform an action, but it doesn't work.  I removed the rendered attribute from the button and magically, the jQuery worked!  So I know its not the code, its because the element isn't rendered and so presumably doesn't exist within the DOM when the page is loaded.

 

So my question - how can I get the function to work on a button which is not rendered at load time?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
Use jQuery "live" function if you want to be able to hook to elements that may not be loaded when the page is rendered initially. This function monitors for the relevant event on any element that appears during the life cycle of the page that matches the selector given to the live function. See more details on the jQuery documentation page.

All Answers

Kamatchi Devi SargunanathanKamatchi Devi Sargunanathan
can you explain, that you need to call a function through a jquery while button is clicked?

Or at what scenario you need to do this?
sfdcfoxsfdcfox
Use jQuery "live" function if you want to be able to hook to elements that may not be loaded when the page is rendered initially. This function monitors for the relevant event on any element that appears during the life cycle of the page that matches the selector given to the live function. See more details on the jQuery documentation page.
This was selected as the best answer
ministe_2003ministe_2003

Ah, thanks sfdcfox, that helped.  The live method is depreciated so the docs say to use .on instead.  I tried

$j( "#nextBtn1" ).on( "click", function() {

 but that didnt work, however

$j( "body" ).on( "click", "#nextBtn1", function() {

 does, presumably because the action is attached initially to the body tag and so will work with anything rendered at the time of the click.

 

To answer the first question, I'm attaching jQuery to a button purely to apply effects.  I'm new to jQuery and  I'm just trying to make the user experience a bit more pleasant.

 

Thanks for the replies!