GWR
GWR

Reputation: 2008

jQuery Not Working on Dynamic Content after DOM Changes

I have a web form which has 2 versions. When the page is loaded, a default version (lets call it version 1) is shown inside of a div <div id="oAuthPanel">.

In these forms themselves (in both versions), there is a pair of radio buttons, wrapped in <span> tags which are used to switch form versions via jQuery + Ajax.

When the user clicks on the 2nd radio button (or anywhere within the <span> tag which surrounds it), some jQuery captures the click and retrieves version 2 of the form via .load(). Version 2 of the form should now be the content inside of the div <div id="oAuthPanel">. If the user clicks on the first radio button the jQuery should retrieve version 1 of the form again.

However, the switching isn't working smoothly. The 2nd version of the form loads fine (by clicking the 2nd radio button) the first time after loading the page. However, if I click that radio button first. But after that, it won't swtich back when I click the first radio button etc.

Here is the jsFiddle to give an idea of the code (but it is on a dev box so the ajax part won't work).

https://jsfiddle.net/robarwebservices/6xkoy7bz/1/

How can I make this work as expected?

Upvotes: 1

Views: 600

Answers (1)

GWR
GWR

Reputation: 2008

The issue was in the way that my jquery was written to handle the switching. Since the form itself was dynamic, I had to change lines like this:

$('#oaSpanLinkNative').click(function () {

to

$(document).on('click', '#oaSpanLinkNative', function () {

The reason this works was explained in the top two answers here:

Jquery function doesn't work after Ajax call

Upvotes: 3

Related Questions