Hello I have a simple page that allows a user to enter a binary value which is then converted into a decimal value. However, I am using two fields, one for entering the binary value, and the other to display the result in decimal.
I want to only use on field, so when the user enters the binary value, the result in decimal will appear in the same box that they entered input. Here is my current code:
<?php
if (isset($_POST['submit']))
{
$str = $_POST['binToDec'];
$pos = 0;
$sum = 0;
$tempSum = 0;
$strLength = strlen($_POST['binToDec']) - 1;
$powerOfTwo = 1;
if ( $str{strLength} == 1 )
$sum += 1;
for ( $i = $strLength - 1; $i >=0; $i-- )
{
$tempSum = ($powerOfTwo *= 2);
if ( $str{$i} == 1 )
$sum += $tempSum;
}
}
?>
<html><body>
<form method="post" action="#">Binary value: <input name="binToDec"><br />
Result: <input value="<?php if (isset($sum)) echo $sum ?>"><br />
<input type="submit" name="submit" value="Convert">
</form>
<body></html>
This this little modification will solve your issue:
<form method="post" action="#">
Binary value: <input name="binToDec" value="<?php if (isset($sum)) echo $sum ?>"><br />
<input type="submit" name="submit" value="Convert">
</form>
This code is setting value on the input you've used for the POST action of the form.
Here's the code:
<?php
if (isset($_POST['submit']))
{
$str = $_POST['binToDec'];
$pos = 0;
$sum = 0;
$tempSum = 0;
$strLength = strlen($_POST['binToDec']) - 1;
$powerOfTwo = 1;
if ( $str{strLength} == 1 )
$sum += 1;
for ( $i = $strLength - 1; $i >=0; $i-- )
{
$tempSum = ($powerOfTwo *= 2);
if ( $str{$i} == 1 )
$sum += $tempSum;
}
}
?>
<html><body>
<form method="post" action="#">
Binary value: <input name="binToDec" value="<?php if (isset($sum)) echo $sum ?>" />
<input type="submit" name="submit" value="Convert">
</form>
<body></html>
Try to use the onkeyup or onkeydown or onchange to show the value in the same box, using
javascript,
example,
function Conversion(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
Enter: <input id="bin" name="" type="text" onkeyup="Conversion(this)" size=20>
Store return value to the same text box using the javascript like by using document.getElementbyId