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. Both functions are in a static file called "main.js" 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>
Before putting both JavaScript functions into a static file, I experimented with putting the script tags at the start or at the end of the in all manner of combinations. So far, the advice suggested here Why does jQuery or a DOM method such as getElementById not find the element? hasn't been helpful for me. I've tried a lot of the suggestions in the answers there but I'm still having the same problem.
The error
at HTMLButtonElement.button.onclick (main.js:15)
still persists which is showPage(this.dataset.page);
this line in the showPage function.
I'm really stuck on this. Any advice is greatly appreciated.