Reputation: 386
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?
Upvotes: 1
Views: 719
Reputation: 23
function enterCommand () {
var field = document.getElementById("commandfield");
var input = field.value;
alert(input);
}
Try this,I think you put the script in head tag,not the bottom of the body tag.
So could not GET that Node
Upvotes: 1
Reputation: 1
I tried it, and this works:
<script type="text/javascript">
function enterCommand () {
var field = document.getElementById("commandfield");
var input = field.value;
window.alert(input);
}
</script>
<input type="text" name="commandfield" id="commandfield">
<button type="button" onclick="enterCommand()">Enter</button>
Upvotes: 0
Reputation: 48761
Select the element inside the function:
function enterCommand () {
var field = document.getElementById("commandfield");
if (field) {
var input = field.value;
alert(input);
}
}
This will select the element given the state of the DOM at the time the event occurs.
Upvotes: 4