0

I'm trying to implement a function that will create new divs inside another div based on the number typed by user. I wanted to do this with addEventListener to the input and ran a test to check if it even works. But it doesnt and I dont know what im doing wrong. Here is my HTML code:

<form>
    <p>Pick how many dice you want to roll:</p>
    <input id="diceNumber" type="number" name="diceNumber">
</form>

and JS part:

var numInput = document.querySelector("input");

numInput.addEventListener("change", function(){
alert("test");
});
Matti Mazur
  • 83
  • 2
  • 8
  • 3
    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) – Sebastian Simon Mar 15 '17 at 09:55
  • It actually works https://jsfiddle.net/s8oLofLm/ I think the javascript is not well loaded in your document. – R. Giovanetti Mar 15 '17 at 09:56
  • From this jsFiddle: https://jsfiddle.net/eekrmjfq/ the `alert` is displayed – ValLeNain Mar 15 '17 at 09:56
  • 1
    @Ganoninc Of course it works on JSFiddle, because they wait for the HTML to be loaded before executing the JS by default. – Sebastian Simon Mar 15 '17 at 09:57
  • @ValLeNain Don’t edit the JSFiddle into the question: it neither helps to reproduce nor to solve the problem. It’s fine as a comment, but it shouldn’t be part of the question. – Sebastian Simon Mar 15 '17 at 10:01
  • @Xufox: a well written, JS related, post has a jsFiddle associated with. And it does help: it tells the problem does not come from the Js code – ValLeNain Mar 15 '17 at 10:12
  • 1
    @ValLeNain If a question requires a jsFiddle example then it's a bad question. The issue should be able to be represented simply and cleanly, in a manner that any experienced developer should be able to understand by just reading it. Like this question. – Reinstate Monica Cellio Mar 15 '17 at 11:45

2 Answers2

3

How are you including your javascript file in the html document? It may be possible that your JS code is being executed before the html is loaded.

0

It is hard to answer only with these 2 snippets. My guess is that you have something like

<html>
<head>
<script>
var numInput = document.querySelector("input");

numInput.addEventListener("change", function(){
alert("test");
});
</script>
</head>
<body>
<form>
    <p>Pick how many dice you want to roll:</p>
    <input id="diceNumber" type="number" name="diceNumber">
</form>
</body>
</html>

In this case, the script will be executed before the dom is loaded which is why the code cannot find the input.

you either have to wait that the dom is ready or move the script block after the definition of the input.

Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77