0

This has been asked 100x before but after reading a lot of those posts I'm still not sure what I'm doing wrong. The script is only executed when you press the button (so the textbox should exist in the DOM by the time the code is executed), Visual Studio even lets me autocomplete the getElementByID argument to inputField. Yet somehow it doesn't get the element and 'null' is printed on my screen.

My code is:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

    <!-- input field + button, and an empty value field --> 
    <input type="text" id="inputField" value="" />
    <input type="button" onclick="printType()" />

</body>


<script>

    function printType() {
        console.log(document.getElementById(inputField).value); //first try to get the value the regular way
        console.log(
            get_type(
            document.getElementById(inputField)
            )
            ); //also try get_type to see if it exists, we're expecting a string
    }



    //stole this function from a stackoverflow post
    function get_type(thing) {
        if (thing === null) return "[object Null]"; // special case
        return Object.prototype.toString.call(thing);
    }



</script>

</html>
Plumpie
  • 355
  • 1
  • 3
  • 17

2 Answers2

5

You're missing quotes:

document.getElementById(inputField);

Should be:

document.getElementById('inputField');
Schlaus
  • 15,686
  • 10
  • 31
  • 62
  • That solved it, thank! Strange Visual Studio didn't catch it but in Js everything is possible I guess – Plumpie Jul 04 '16 at 18:37
0

Based on @Schlaus answer, I created a jsfiddle with correct answer.

function printType() {
    console.log(document.getElementById('inputField').value); //first try to get the value the regular way
    console.log(
    get_type(
      document.getElementById('inputField')
    )
    ); //also try get_type to see if it exists, we're expecting a string
}