Reputation: 38
I'm working on creating a website that can translate a base 10 number into Binary for extra credit in a class I am taking.
My website URL is: http://loganf.tynken.com
. My goal is to have the user enter a number into a form, for that number to become a string in a <h4>
tag, and to be used by JavaScript to take the string, make it a number, and to then use more code to show the binary number on the screen.
I'm having trouble getting the string into a number.
The JavaScript shown here is now my final product, but a way to try to make the number appear.
var base10, base2, v2_0, v2_1, v2_2, v2_3, v2_4, v2_5, v2_6, v2_7,
v2_8, v2_9, v2_10, v2_11, v2_12;
base10 = document.getElementById('base10');
base2 = document.getElementById('base2');
v2_0 = 1;
v2_1 = 2;
v2_2 = 4;
v2_3 = 8;
function assignvarbinaryvalue() {
var binaryNumber = Number(base10);
var newEl = document.createElement('h4');
var newText = document.createTextNode(binaryNumber);
newEl.appendChild(newText);
var position = document.getElementById('binaryID');
position.appendChild(newEl);
}
<h1>Binary Translator</h1>
<p><div id="base10"><?php echo $_GET['base10']; ?></div><p id="binaryID"></p></p>
Upvotes: 0
Views: 49
Reputation: 40084
You are not grabbing the value:
var base10, base2, v2_0, v2_1, v2_2, v2_3, v2_4, v2_5, v2_6, v2_7, v2_8, v2_9, v2_10, v2_11, v2_12;
base10 = document.getElementById('base10');
base2 = document.getElementById('base2');
v2_0 = 1;
v2_1 = 2;
v2_2 = 4;
v2_3 = 8;
v2_4 = 16;
//v2_5 = 32;
//v2_6 = 64;
//v2_7 = 128;
//v2_8 = 256;
//v2_9 = 512;
//v2_10 = 1024;
//v2_11 = 2084;
//v2_12 = 4096;
function assignvarbinaryvalue() {
var binaryNumber = parseInt(base10.innerHTML);
var newEl = document.createElement('h4');
var newText = document.createTextNode(binaryNumber);
newEl.appendChild(newText);
var position = document.getElementById('binaryID');
position.appendChild(newEl);
}
assignvarbinaryvalue()
Upvotes: 0
Reputation: 1662
var base10 = document.getElementById('base10');
var base2 = document.getElementById('base2');
document.getElementById('submit').onclick=function() {
var number=parseInt(base10.value);
base2.value=decimalToBinary(number);
}
function decimalToBinary(n){
var binaryNumberStr = "";
var binaryNumber=0;
var step=0;
while (Math.pow(2, step)<n)
{
step+=1;
}
for(var i=step; i>=0; i--){
var c=Math.floor(n/Math.pow(2, i))
n-=Math.pow(2, i)*c;
binaryNumber+=Math.pow(2, i)*c;
binaryNumberStr+=c;
}
//binaryNumberStr+=(n-binaryNumber)
return binaryNumberStr;
}
<p>Number:</p>
<input type="text" id="base10" name="base10" size="15" maxlength="30">
<input type="submit" id="submit" name="submit" value="submit">
<input type="text" id="base2" name="base2" disabled size="15" maxlength="30">
Upvotes: 1
Reputation: 504
If you want to convert string into number you can just use javascript function
parseInt()
Upvotes: 0