I am trying to get rid of jQuery from my code and for some reason, this jQuery works “$(“#modal-body”).html(post_template);” but when I convert to pure vanilla JavaScript “document.getElementById(‘modal-body’).innerHTML=post_template.outerHTML” the html looks fine, but it breaks a function below that is called by “post_template.addEventListener(‘submit’, async (e) =>”.
Here is the function I am trying to rid of jQuery. I commented out the piece that makes it work with jQuery.
function build_post_modal() {
post_template=document.getElementById('post_template')
document.getElementById('modal-title').innerHTML='Post'
//For some reason this code breaks the addEventListener code below
document.getElementById('modal-body').innerHTML=post_template.outerHTML
//This code does what I want, but uses jQuery
//$("#modal-body").html(post_template);
footer="<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>"
document.getElementById('modal-footer').innerHTML=footer
//Push template back to DOM on close
$('#siteModal').on('hide.bs.modal', function (e) {
$("#post_modal").html(post_template);
//TODO get typed context to push back to main window
})
const fields = {
csrf_token: {
input: document.getElementById('csrf_token'),
error: document.getElementById('csrf_token-error')
},
body: {
input: document.getElementById('body'),
error: document.getElementById('body-error')
}
}
//This code breaks when I use the pure javascript method for making the modal-body
post_template.addEventListener('submit', async (e) => {
e.preventDefault();
const response = await fetch('/_submit_post', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
csrf_token: fields.csrf_token.input.value,
body: fields.body.input.value
})
});
if (response.ok) {
$('#siteModal').modal('hide')
jFlash(await response.text())
} else {
const errors = await response.json();
Object.keys(errors).forEach((key) => {
fields[key].input.classList.add('is-invalid');
fields[key].error.innerHTML = errors[key][0];
});
}
});
};
This is the jinja html that I am trying to pull the template from to style a modal.
<a data-bs-toggle="modal" data-bs-target="#siteModal" onclick="build_post_modal()">
<div class="post d-flex align-items-center">
<img src="{{ current_user.avatar(50) }}" width="50" class="rounded-circle mr-2">
<input class="form-control" id="post_body" placeholder="Make a post..." type="text" value="">
</div>
</a>
<div id="post_modal" style="display: none;">
<form id="post_template" method="POST">
{{ form.csrf_token }}
<div class="text-danger my-2" id="csrf_token-error"></div>
<div class="post d-flex align-items-center">
<img src="{{ current_user.avatar(50) }}" width="50" class="rounded-circle mr-2">
<div class="form-group">
{{ form.body.label }}
{{ form.body(class='form-control', placeholder='Make a post...') }}
<div id="body-error" class="invalid-feedback"></div>
</div>
</div>
</form>
</div>