I have a page with various jQuery calls on initial load (select2, 'onclick' etc.). It's a remote JS form in my Rails app. If the submit fails I have the page reload the form again for the user to correct validations etc.
The issue is all the intial jQuery calls do not persist on the reloaded content (via a .html()
call).
I have found a few posts like this:
Reinitialize jQuery after AJAX call
I have fixed most of the original calls like this which now works fine:
$(document).on('keyup', 'input.item_quantity', function(event){
my code etc...
});
I have others like this which I can't seem to resolve:
$(function() {
$('[data-behavior="select2-parent"]').select2({
ajax: {
url: 'myurl',
dataType: 'json'
}
});
});
These are all the calls on the document loading and not due to user interaction. I can make these load when the user clicks on the inputs but there is a slight delay between the user click and the select2 kicking in. I need this to persist even when I reload content via the .html()
.
Calling this direct after reload in the console works:
$('[data-behavior="select2-parent"]').select2();
I added this to the code where my .html()
is called but the select2 does not initialize and no console errors.
How have these select2 call bind to the initial elements and ones added afterwards? I suspect I may be missing something small or obvious here.
EDIT: The URL in the select2 AJAX config is also dynamic based on other form input values.