I am making a simple encoder/decoder for me and my friend to talk to each other in code, or at least it should be simple. I keep getting the error "Unable to get property 'value' of undefined or null reference" when I try to reference any of my elements. I feel like I am doing something really dumb that is simple to fix, but I can't see it.
I have looked at several related questions already and have been trying a bunch of stuff that has been suggested, but nothing seems to work. By the way, I am using Microsoft Edge if that makes a difference.
var inMsg = document.getElementById("input")
var outMsg = document.getElementById("output")
document.addEventListener('keypress', (event) => {
if (event.key == 'Enter') {
try {
event.preventDefault()
} catch (e) {
console.log(e)
}
try {
console.log(inMsg.value)
} catch (e) {
console.log(e)
}
}
})
<html>
<head>
<script src="./main.js" type="text/javascript"></script>
<style>
</style>
</head>
<body>
<div>
<h2>Paste Coded Message Here -></h2>
<textarea id="input" value=""></textarea>
<textarea id="output"></textarea>
</div>
</body>
</html>
Usually I am able to just log the value no problem, but it says the element is null when I console.log it.
Try adding defer
to your script tag like so:
<script src="./main.js" type="text/javascript" defer></script>
I believe the html parser hasn't reached your inMsg
element by the time the script is executed and so the value of the element is undefined
.
Let me know if that works!