Ошибка Uncaught TypeError: Cannot set property 'innerHTML' of null
означает, что объект, который вы вызываете .innerHTML
, не существует. В вашем случае это строка:
document.getElementById('calculate').innerHTML = calculate
, и вы получаете эту ошибку, потому что у вас нет элемента с id
из calculate
. Если у вас нет этого элемента, вы не можете вызвать для него .innerHTML
.
Вам также необходимо получить данные из полей формы с помощью свойства .value
, а не onclick
property.
См. дополнительные комментарии ниже:
<html>
<head>
<title>Sample Page</title>
<style>
div { margin:1em; } /* adds vertical space before and after each div */
</style>
</head>
<body>
<div>
<!-- You can't have an <h2> if you don't already have an <h1> for it to be
a sub-section of. Don't use HTML elements because of how they style the output.
Use CSS to style. Also, don't use <p></p> to create vertical space. Again, use
CSS for style. -->
<h1> Daily calorie intake</h1>
<div><input type="number" placeholder="your height" id="height" min="1" max="230"></div>
<div><input type="number" placeholder="your age" id="age" min="1" max="120"></div>
<div><input type="number" placeholder="your weight" id="weight" min="1" max="500"></div>
<div>Your sex
<select id="sex">
<option value="1" id="male">male</option>
<option value="2" id="female">female</option>
</select>
</div>
<button>Calculate</button>
</div>
<div id="output"></div>
<script>
// Do your event binding in JavaScript, not in HTML
document.querySelector("button").addEventListener("click", calculate);
// Get references to the elements you'll need (not the value of their onclick properties)
var height = document.getElementById('height');
var age = document.getElementById('age');
var weight = document.getElementById('weight');
var sex = 1;
// You don't need any arguments because you already have references to the fields
// where the data is.
function calculate() {
// Declare the variable the will hold the result and don't use the
// name of the function as the name of the variable
let result = null;
switch(sex) {
// To get the data out of a form field, you must access its .value property
case sex: 1
result = 66.5 * (13.75 * weight.value) + (5 * height.value) - (6.76 * age.value);
break;
case sex: 2
result = 655.1 * (9.56 * weight.value) + (1.85 * height.value) - (4.68 * age.value);
break;
default: 1
}
// Make sure you reference elements that exist and don't use
// .innerHTML when there is no HTML in the string.
document.getElementById('output').textContent = result;
}
</script>
</body>
</html>