I just started learning coding. and i was trying to apply the OOP pradigm to an example.
I am trying to create an object (the character here) and assign its properties as the values input within the html file.
the error that keeps appearing is ‘javascript.js:14 Uncaught TypeError: Cannot read properties of null (reading ‘value’) .
<body>
<label for="namebox">Character Name</label>
<input type="text" name="" id="namebox">
<label for="agebox">Age</label>
<input type="text" name="" id="agebox">
<label for="humanclass">Human</label>
<label for="majinclass">Majin</label>
<input type="radio" name="class1" id="humanclass">
<input type="radio" name="class1" id="majinclass">
<input type="button" value="Create Character" id="creationbtn" onclick='char1.identify()'>
<input type="reset" value="Cancel">
</body>
class Charcreation {
constructor(name, age, charclass) {
this.name = name;
this.age = age;
this.class = charclass;
}
identify() {
console.log('my name is ' + this.name + ' and i am a ' + this.age + ' years old ' + this.class)
}
}
charname = document.getElementById("namebox").value;
charage = document.getElementById('agebox').value;
charselection = document.getElementByName('class1').value;
charclass =
function getClass() {
for (i == 0; i < charselection.length; i++) {
if (charselection[i].checked)
return charselection[i];
}
}
char1 = new Charcreation(charname, charage, charclass())
char1.identify();
Thanks in advance
2
Answers
Have you made sure that the script is firing after the DOM gets rendered?
It’s possible that it is running before the actual HTML has been rendered and that is why
.getElementById("namebox")
is returning null.There are probably other ways to ensure this, but the easiest I know of is just put the script inside of the footer instead of the header.
There are a few errors in your code as @Chris G points out plus some others. Here’s an update to your code with corrections to get a successful output for your
char1.identify();
method.I’ve added some CSS styling that’s not necessary to the output.
When the user clicks on the
#creationbtn
button, code execution needs to retrieve values of the form controls each time. Your original code is retrieving values of theinput
controls when the page is loaded and not each time the button is clicked.