1

I have a function I want to call when dynamically created content comes from ajax. This bit is working fine. I also want to call the function when the class .check_if_checked changes (checkbox checked or radio changed, etc.). I have...

$('.check_if_checked').on('change', '#page-wrapper', function() {
    activate_step_2_button();
});

function activate_step_2_button(){
    //do stuff
}

The .on will just NOT detect changes. If I put

$('.check_if_checked').on('change', '#page-wrapper', function() {
    
});

inside

function activate_step_2_button(){
    //do stuff
}

then it detects ok...... but then I can't directly call the function from other places (there's not a change in that case).

Oh, and if I enter

$('.check_if_checked').on('change', '#page-wrapper', function() {
    activate_step_2_button();
});

into the console everything works.

And yes, I read over JQuery function only works within a function already. This feels like a duplicate of that, but the solution there (and other similar solutions) are just not working.

gtilflm
  • 1,389
  • 1
  • 21
  • 51
  • I don't understand what you are asking. I suspect it is due to the DOM elements changing after the AJAX response is received. The solution in this case would be event delegation, which the link you shared discusses. – 76484 Feb 18 '23 at 23:24
  • @76484: Would that also account for the fact that it works when I enter the code into the console? Also, aren't I already delegating via the `'#page-wrapper'` in `$('.check_if_checked').on('change', '#page-wrapper', function()`? – gtilflm Feb 18 '23 at 23:28
  • Possibly. It depends on the timing of when you add the listener and when the DOM is changed. Yes, you are using delegation, having `.check_if_checked` capture changes to a child `#page-wrapper`. But this looks backwards. I would assume that `#page-wrapper` wraps the page. In which case, it should be `$('#page-wrapper').on('change', '.check_if_checked', function () {})`. – 76484 Feb 18 '23 at 23:52
  • ^this!! I didn't know there was a parent/child relationship! I can accept your answer as "the one" if you want to submit an answer. Thanks! – gtilflm Feb 18 '23 at 23:57
  • Simple, you misunderstood how to use Event delegation using the .on() method. Here's how: `$("#staticParent").on("eventName", ".dynamicChild", fn)` - whereas you inverted the static and dynamic selectors in your code. – Roko C. Buljan Feb 19 '23 at 00:37
  • @gtilflm : I don't think there is anything in what I could post that would add to the Event Delegation post you liked to. But please be sure to up vote that one! – 76484 Feb 19 '23 at 01:32

0 Answers0