转换盒,如何使两个输出盒都工作?

时间:2016-11-10 19:59:17

标签: javascript html type-conversion converter

我正在做一个转换器的项目。当我在数字框中输入一个数字时,它在box2中显示正常。但是当我尝试在box2中输入一个数字时,它不会在box1中显示答案。谁能帮我?我不知道jquery,我是html和javascript的首发。希望有人可以帮助我。感谢

function NumberToSquare(num)
{ 
var sqrt; 
sqrt = Math.sqrt(num); 
return sqrt; 
} 

function SquareToNumber(sqrt)
{ 
var num; 
num = Math.pow(sqrt,2); 
return num; 
} 
<html>
<head>
<title>Program Assignment 5</title>

<script type = text/javascript src = "calculate.js"> </script> 

<script type="text/javascript">
function ConvertToSqrt()
  //Assumes: Number contains a number
  //Results: displays the square root in box2
  {
    num = parseFloat(document.getElementById('box1').value);
    sqrt = NumberToSquare(num);
    box2.value=sqrt;
  }
  
  function ConvertToNum()
  //Assumes: Square contains a number of square root
  //Results: displays the number in box1
  {
    sqrt = parseFloat(document.getElementById('box2').value);
    num = SquareToNumber(sqrt);
    box1.value=num;
  }
</script>

</head>  

<body>
<div style="border: solid; width: 300px; background-color: #83CAFF">

<table>
<th></th> <th>Square Root Calculation</th>
<tr>
<th>Enter Number:</th><th><input type="number" id="box1" value=""></th>
<tr>
<th>SquareRoot:</th><th><input type="number" id="box2" value=""></th>
<tr>
<th></th><th><input type="button" value="Calculate" onclick="ConvertToSqrt(); ConvertToNum();">
</table>
</div>

1 个答案:

答案 0 :(得分:0)

如果它有帮助,这里有一个快速的样本。它不漂亮,但你可以拿出你需要的东西,并用你自己的东西。

<html>
<head>
    <title></title>
    <script>
        function calc(which) {
            var newVal;
            if (which == "sqrt") {
                newVal = parseFloat(document.getElementById("num").value);
                newVal = Math.sqrt(newVal);
            }
            else if (which == "num") {
                newVal = parseFloat(document.getElementById("sqrt").value);
                newVal = Math.pow(newVal, 2);
            }

            document.getElementById(which).value = newVal;
        }
    </script>
</head>
<body>
    <div style="width:400px;padding:25px;display:inline-block;line-height:150%;background-color:#83CAFF;font-weight:bold;border:solid 1px black;">
        <div style="width:200px;float:left;">
            <label>Number:</label>
            <br />
            <label>SquareRoot:</label>
        </div>
        <div style="width:200px;float:right;">
            <input type="number" id="num"/>
            <br />
            <input type="number" id="sqrt"/>
        </div>
        <button type="button" style="width:100%;" onclick="calc('sqrt');">Calc Sqrt</button>
        <button type="button" style="width:100%;" onclick="calc('num');">Calc Num</button>
    </div>
</body>
</html>