Cant get value of an input

I dont know if this is an bug or something. I have tried everything but I cant get the value of this input, but if I type the exact same code in console, then it somehow works.

<input class="form-control needed-field" id="myid" name="varname">
var input = document.getElementById("myid").value

I have tried to save the input to a variable then then from the variable get the value because I saw that as a solution on the internet, but that also didnt work.