简体   繁体   中英

javascript variable undefined or null

couldn't find a specfic answer elsewhere. I'm totally new to JS and trying to pull a value out of a form and write it to the page. The result when I try to write ProductName is undefined, and when I try to write ProductNameElement is null. I'm sure it's to do with the form values being empty when the page loads but not sure after that...

<script>

    var ProductNameElement = document.getElementById("ProductName");
    var ProductName = ProductNameElement.value;

    function showname(){

    document.write(ProductName);

    }

</script>

<h2>Revenues</h2>

<div class="number">Product Name: <input type="text" id="ProductName" value=""></input></div>

<input type="button" value"showname" onclick="showname();"></input>

You are running the first two lines of your script too early BEFORE the elements in your page have been parsed and placed into the DOM. Because of that, the ProductName element doesn't exist yet when you're trying to find it with document.getElementById("ProductName"); .

Place your script right before the </body> tag and then all your page elements will be available when you run your script. Or, just put all your code in the showname function that isn't called until the click event.

function showname(){

    var ProductNameElement = document.getElementById("ProductName");
    var ProductName = ProductNameElement.value;

    document.write(ProductName);
}

And, as others have said, using document.write() after the documented has been loaded will cause the existing document to be cleared and a new empty document will be created. This is pretty much never what you want. If you're just doing this for debugging, use console.log(ProductName) and look at the debug console.

You'll have to get the element and the value inside the function, otherwise they aren't available, and the change of the value isn't caught

<script>
    function showname(){
        var ProductNameElement = document.getElementById("ProductName");
        var ProductName = ProductNameElement.value;

        document.write(ProductName);
    }
</script>

<h2>Revenues</h2>

<div class="number">
    Product Name: <input type="text" id="ProductName" value="" />
</div>

<input type="button" value"showname" onclick="showname();" />

FIDDLE

And inputs are self closing, and you should stop using document.write , it will overwrite the entire document and remove everything that is currently there !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM