In a django project, I've set up a JavaScript function to select/block certain pages. I have another JavaScript function for the pages that are being loaded. This function has an onclick event listener that submits text to a form field. The problem I'm having is that when I click a button to add text to a form field, the entire page disappears. The exact error message showing in the console is...
Uncaught TypeError: Cannot read property 'style' of null
at showPage (players:6382)
at HTMLButtonElement.button.onclick (players:6388)
Here's the function controlling showing/blocking of individual pages.
function showPage(page) {
document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';})
document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message)
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('button').forEach(button => {
button.onclick = function() {
showPage(this.dataset.page); ---(This line in error message)
}
});
});
Here's an example from the html template of a button targeted by this function.
<button class="posbutton" data-page="page1">QB</button>
This is the function that submits text to a form field.
function myFunction(txt) {
var myTxt = txt;
if (txt.includes('QB')) {
document.getElementById("QB_name").value = myTxt;
}
else if (txt.includes('RB')) {
document.getElementById("RB_name").value = myTxt;
}
else if (txt.includes('WR')) {
document.getElementById("WR_name").value = myTxt;
}
else if (txt.includes('TE')) {
document.getElementById("TE_name").value = myTxt;
}
else if (txt.includes('K')) {
document.getElementById("K_name").value = myTxt;
}
}
Here's an example of the html element targetted by the showPage function. It also contains a line with the button that's linked to the myFunction for submitting text.
<tbody id="page1">
{% for q in QBpage %}
<tr>
<th scope="row">
</th>
<td><h6>{{ q.player_name }}</h6></td>
<td><input type="button" class="btn btn-outline-primary btn-sm m-0 waves-effect" onclick="myFunction('{{ player_data.player_name }} {{ player_data.position }}')">Add</input></td>
<td><h6> {{ q.team }} </h6></td>
<td><h6> {{ q.position }} </h6></td>
<td><h6>{{ q.points }}</h6></td>
</tr>
{% endfor %}
</tbody>
I've looked around at similar questions and tried positioning my tags just before the {% endblock %} tag in the html template, but no good. I've also tried positioning the scripts at the start of the template. As a JavaScript novice, I'm not sure where else to look and would really appreciate any opinions on where I'm going wrong here.