Reputation: 11
Absolute beginner and trying to create a very simple decimal to binary converter. I know there exist easier/cleaner ways built into Javascript for converting to different number bases, but I liked creating my own script from scratch. Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>GetBit</title>
</head>
<body>
<h1>Decimal to Binary</h1>
<p><input type="number" min="0" id="decimal"</p>
<button type="button" onclick="getBit()">Submit</button>
<p>here is your answer:</p><p id="binary"></p>
<script>
function getBit() {
var n = document.getElementById("decimal").value;
if (n >= 2) {
bit = (n % 2) + "" + bit;
return getBit(n = Math.floor(n/2), bit)
} else {
bit = 1 + "" + bit;
return bit
}
var bit = document.getElementById("binary").innerHTML;
}
</script>
</body>
</html>
I am sure this is atrocious code, but I am doing trial by fire. Really, on the whole, I would like to understand better how user input and Javascript functions interact, and the best practice for placing user input into variables and then using those value to output a new value (like taking a decimal number and outputting binary).
I had tested my getBit() function in the console, and it returned the correct binary. I changed it slightly for my HTML. Here's the original JS that worked:
function getBit(n, bit = "") {
if (n >= 2) {
bit = (n % 2) + "" + bit;
return getBit(n = Math.floor(n/2), bit)
} else {
bit = 1 + "" + bit;
return bit
}
}
I'm stumped on how this should be translated into a element in HTML. Any help is appreciated.
Upvotes: 1
Views: 178
Reputation: 28236
You need to turn your expression around:
document.getElementById("binary").innerHTML = bit
Your original expression would have assigned the current HTML-content of the chosen DOM element into your variable bit
.
document.querySelector('#decimal').addEventListener('input',function(ev){
document.getElementById("binary").innerHTML=getBit(ev.target.value)});
function getBit(n, bit="") {
if (n >= 2) {
bit = (n % 2) + "" + bit;
return getBit(n = Math.floor(n/2), bit)
} else {
bit = +n + "" + bit;
return bit
}
}
<h1>Decimal to Binary</h1>
<p><input type="number" min="0" id="decimal" placeholder="enter a decimal number">
<p>in binary this is:</p>
<p id="binary"></p>
I changed my event listener to look for input
events now and also the statement in your else
condition to bit = +n + "" + bit;
as otherwise the decimal 0
would have been "converted" to 1
.
Upvotes: 1