0

I was recently introduced to Web Storage on my current course and have been tasked with taking input from a text field (input) using a button, then creating a key and value for this text field data. It seemed rather trivial. I produced some code in attempt to get it working. However the code did not work as expected.

Here is the (non-working) code I managed to produce:

HTML:

<!doctype html>
<html>
<head>
    <title>Test</title>
    <script src="app.js" charset="utf-8"></script>
    <meta charset="utf-8">
</head>
<body>
    <p>Forename:</p>
    <input type="text" id="FName"><br>
    <button type="button" id="Submit">Submit</button>
</body>
</html>

JS:

var SubmitButton = document.getElementById('Submit');
var TextField = document.getElementById('FName');

SubmitButton.addEventListener('click', function(e){
    ToTextField();
});

function ToTextField(){
    var input = document.getElementById("FName").value;
    localStorage.setItem("Text", input);
}

Though this code does not work, I have analyzed the developer tools tab in my browser (Firefox), and noticed that I get the following error:

TypeError: SubmitButton is null [Learn More]    app.js:6:1

If I then enter the following lines of JS into the Console (which are the same in my file), the submit button seems to work as I expected it. I can't figure out the problem:

var SubmitButton = document.getElementById('Submit');
SubmitButton.addEventListener('click', function(e){
    ToTextField();
});

Can anyone spot the problem I am having here? Thanks :)

dhilt
  • 18,707
  • 8
  • 70
  • 85
bhLD
  • 13
  • 5
  • 2
    Try moving the script tag to just before the closing body tag. – Nisarg Shah Nov 12 '17 at 15:12
  • Move ` – dhilt Nov 12 '17 at 15:14
  • Ah yes, I understand that these elements would not exist at the time of script execution due to the script being loaded first. Thanks a lot and sorry for the duplicate. – bhLD Nov 12 '17 at 15:19

0 Answers0