Reputation: 215
I am trying to write a quiz in pure javascript that loads new questions from an array and fills a table when the user clicks next. A seemingly simple problem I have is that I cannot get an event listener to work when the user clicks the next button. On JSFiddle it works, but it won't work on my end and I have no idea why. Just as a test I have it alerting if the button is pressed. I have also tested multiple different ways of checking if the document has loaded before executing to no avail.
HTML
<body>
<table class="center">
<tr>
<th id='question' colspan="2">question</th>
<td colspan="2"></td>
</tr>
<tr>
<td id="answer0">Choice 1</td>
<td><input id="radio0" type="radio" name=que_1 value="1" required/></td>
</tr>
<tr>
<td id="answer1">choice 2</td>
<td><input id="radio01" type="radio" name=que_1 value="1"/></td>
</tr>
<tr>
<td id="answer2">choice 3</td>
<td><input id="radio02" type="radio" name=que_1 value="1"/></td>
</tr>
<tr>
<td id="answer3">choice 4</td>
<td><input id="radio03" type="radio" name=que_1 value="1"/></td>
</tr>
</table>
<div>
<input type="button" id="next" value='Next'>
</div>
</body>
Javscript
document.getElementById("next").addEventListener("click", function() {
alert("works");
});
Thank you in advanced.
Upvotes: 0
Views: 57
Reputation: 780929
Make sure you bind the event handler after the DOM is loaded:
window.addEventListener('load', function() {
document.getElementById("next").addEventListener("click", function() {
alert("works");
});
});
Upvotes: 1