I know this is an extremely basic question but I’m very new to (non-HTML) programming and after taking most of the JS tracks on CodeAcademy, I’m still struggling to make any of the things I’ve learned actually work.
So I decided as a challenge to myself to design a simple JavaScript-based command line. Of course, the very first actual code that I write refuses to work, despite constant fiddling.
Here’s the HTML (well, the relevant bit):
<input type="text" id="commandfield"></input>
<button type="button" onclick="enterCommand()">Enter</button>
And here’s the Javascript:
var field = document.getElementById("commandfield");
function enterCommand () {
var input = field.value;
alert(input);
}
…And no alert shows. I tested a plain string alert, and it worked fine, so I know the problem lies with the getting value of #commandfield. What am I doing wrong?
Select the element inside the function:
This will select the element given the state of the DOM at the time the event occurs.