0

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.

Austin Shoecraft
  • 215
  • 1
  • 3
  • 16
  • 1
    Did you put the JS code before or after the button? And if before, did you put it in a `window.load` or something? – putvande Jan 27 '15 at 17:31
  • Yes, it sounds like you have not attached the script to the page correctly. To test this, add `alert('loaded');` directly into the root of the javascript. If you don't see the alert, this is your issue! – Octopoid Jan 27 '15 at 17:36
  • (As putvande says, it is also sensible to add anything which interacts with the DOM via `getElementById` etc. into the body onload handler.) – Octopoid Jan 27 '15 at 17:38
  • both of you got it, I moved the scripts from the head to the bottom of the body. Thank you – Austin Shoecraft Jan 27 '15 at 17:38
  • possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Teemu Jan 27 '15 at 17:38

1 Answers1

1

Make sure you bind the event handler after the DOM is loaded:

window.addEventListener('load', function() {
    document.getElementById("next").addEventListener("click", function() {
        alert("works");
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612