I'm going through a book and it seems to be right, but the following code keeps giving me the error: Cannot set property 'nodeValue' of null. The code makes sense to me, but I don't understand why it can't clear the text value when clicking the clear button.
var clear = function(){
$("miles").firstChild.nodeValue = "";
$("gallons").firstChild.nodeValue = "";
$("mpg").firstChild.nodeValue = "";
}
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
$("clear").onclick = clear;
}
Html
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate MPG"><br>
<input type="button" id="clear" value="clear"><br>
</section>
I think what you want is this where you use the .value property on the input fields directly:
var clear = function() {
$("miles").value = "";
$("gallons").value = "";
$("mpg").value = "";
}
Here's an explanation of what was going on. Now that we can see your full page and see that $ is document.getElementById(), the issue is that you are some of those nodes don't have a firstChild.
For example the object with an id="miles" is an input tag and it has no children so .firstChild is null.
In this line:
$("miles").firstChild.nodeValue = "";
$("miles") gets you the DOM object.
$("miles").firstChild returns null because there are no children of that DOM object.
$("miles").firstChild.nodeValue = ""; is an error because $("miles").firstChild is null and null doesn't have a property .nodeValue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With