I am trying to make an input in which I pass a number and when I click on a button it multiplies it by two. And it returns the result in a paragraph below the input. I tried to multiply counter + is the value that I pass to the input by 2 but it gives me as a result that btnStart is null. I don't know if the problem is in the multiplication logic or directly in the button function.
const counter = document.querySelector('#cowCounter');
const btnStart = document.querySelector('#btn');
const result = document.querySelector('#textResult');
btnStart.addEventListener("click", start);
function start(){
counter.value * 2;
return result = counter;
}
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cows</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div>
<h1>COWS</h1>
<h1>COWS</h1>
</div>
<div>
<h2>The Other World</h2>
</div>
<div>
<p>Let's start with production</p>
</div>
<div class="inputClass">
<label for="cowCounter">Use only numbers from 1 to 20</label>
<input id="cowCounter" value="0" type="text" >
<button type="button" id="btn">GO!</button>
<br>
<p id="textResult"></p>
</div>
<div>
<img id="cowImg" src="img/pngegg.png" alt="vaca">
</div>
</body>
</html>
First, I would assign the HTML elements by their id with document.getElementById. Then, the value of an input obtained by
.value
is of type text, so you have to convert it to an integer (byparseInt
) And sinceresult
it is a<p>
you should show the result in thatinnerHTML
of that<p>
(that is, what is inside<p>
and</p>
)