How could you show a bootstrap alert on mouseover of a choices field in a django form?
I have a questionnaire based on django form and I need to show a note if a user hovers or clicks on a question before it submits. The django form is loaded in from a custom question and question choices model.
I had some luck with custom question formatting prior by handing django form label and choices a mark_safe str with html formatting of the title and options within. I took it a step further for this and attempted to put in some java script as well. Though it does not show anything on mouseover of the choice. In this case answer.content would be the individual choice underneath the question. Below is my mark_safe code which is only called when there is an explanatory_note for this answer choice, it is called right before handing it to django form typed choice field. I tried having it within the html page, but it would not work as it wouldn't be connected to an individual choice under a question. I have confirmed that the following str is correctly handed to the django form and used as a choice. It does correctly display answer.content.
mark_safe("<p id=\"" + str(n) + "\">" + answer.content + "</p> \n"
"<script>\n"
"const alert" + str(n) + " = document.getElementById(\'" + str(n) + "\')\n"
"if (alert" + str(n) + ") {\n"
" alert" + str(n) + ".addEventListener(\'mouseover\', () => {\n"
" appendAlert(\'" + answer.explanatory_note.text + "\', \'primary\')\n"
" })\n"
"})\n"
"</script>\n")
Below you can also see some of the html loading the individual form and the java script which should create the alert.
<div id="liveAlertPlaceholder"></div>
<form action="" name='question' id='question' method="POST">
<div class="card mb-4 mt-4">
<div class="card-body">
{% csrf_token %}
{{ form }}
</div>
</div>
<input class="btn btn-success mb-4" type="submit" value="next" />
</form>
<script>
const alertPlaceholder = document.getElementById('liveAlertPlaceholder')
const appendAlert = (message, type) => {
const wrapper = document.createElement('div')
wrapper.innerHTML = [
'<div class="alert alert-${type} alert-dismissible" role="alert">',
' <div>${message}</div>',
' <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
'</div>'
].join('')
alertPlaceholder.append(wrapper)
}
setTimeout(function() {
bootstrap.Alert.getOrCreateInstance(document.querySelector(".alert")).close();
}, 3000)
</script>
If there is an alternative without javascript and/or bootstrap alerts I would love to hear it. I just need a informational note to pop up when a user hovers over or clicks on a choice.