This may sound stupid but i wrote some code to convert binary into a normal number. I have a button that you have to press which runs the entire function. However, without clicking the button the function launched.
let button = document.getElementById("submit");
let binary;
let result = document.createElement("h1");
result.className = "answer";
button.addEventListener("click", calc());
function calc(){
binary = document.getElementById("binary").value;
result.textContent = "The Result is: " parseInt(binary, 2);
document.body.appendChild(result);
console.log('here');
}
When i load the page the 'The result is' text is already there and when i do click it it wont console log or change the value. This may be stupid but i cant figure it out thanks in advance.
CodePudding user response:
The issue I saw from your code is that you called the function calc()
in the addEventListener method, instead, you should write it like this button.addEventListener("click", calc);
, you should pass calc
and not calc()
.
CodePudding user response:
Use This :
let button = document.getElementById("submit");
let binary;
let result = document.createElement("h1");
result.className = "answer";
button.addEventListener("click",(e)=>{
e.preventDefault();
calc();
});
function calc(){
binary = 1000101; // get binary
result.textContent = "The Result is: " parseInt(binary, 2);
document.body.appendChild(result);
console.log('here');
}
<button id ="submit">
Submit
</button>
<br>