DJ Madeira
DJ Madeira

Reputation: 386

Returning the value of a text field to JavaScript

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

Answers (3)

regou
regou

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

wiredvision
wiredvision

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

I Hate Lazy
I Hate Lazy

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

Related Questions