简单的javascript单位转换器不工作

时间:2017-12-13 16:23:33

标签: javascript php

我试图让一个简单的转换器工作。目前没有输入字段可用。 我可以通过PHP获得价格变量吗?

<h1 style='font-size:46px'>1 DOLLAR = <p id="currentprice" type="number"><?php $url = "https://api.fixer.io/latest?base=USD"; $json = file_get_contents($url); $json_data = json_decode($json, true); $price = $json_data["rates"]["BRL"]; echo $price; ?></p></h1>
How many Dollars?
<input oninput='finalAmountUSD()' onchange='finalAmountUSD()' style='font-size:23px;height:45px' type='number'  class="buy buyinput form-control" id='usdamount' required value='0.00000000' tabindex="1" />
How many BRL?
<input oninput='finalAmountBRL()' onchange='finalAmountBRL()' style='font-size:23px;height:45px' type='number'  class="buy buyinput form-control" id='brlamount' required value='0.00' tabindex="2" />

<script>
function finalAmountUSD()
{
  x = document.getElementById('currentprice').value;
  y = document.getElementById('usdamount').value;
  z = document.getElementById('brlamount').value;
  document.getElementById('usdamount').value = x * z;
}
function finalAmountBRL()
{
  x = document.getElementById('currentprice').value;
  y = document.getElementById('usdamount').value;
  z = document.getElementById('brlamount').value;
  document.getElementById('brlamount').value = x * y;
}
</script>

2 个答案:

答案 0 :(得分:0)

function finalAmountUSD()
{
  x = parseFloat(document.getElementById('currentprice').value);
  z = parseFloat(document.getElementById('brlamount').value);
   
  document.getElementById('usdamount').value = x * z;
}
function finalAmountBRL()
{
   x = parseFloat(document.getElementById('currentprice').value);
   z = parseFloat(document.getElementById('usdamount').value);
   
  document.getElementById('brlamount').value = x * z;
}
<h1 style='font-size:46px'>1 DOLLAR = <input id="currentprice" type="number" value="0.7">BRL</p></h1>
How many Dollars?
<input onblur='finalAmountBRL()' style='font-size:23px;height:45px' type='number'  class="buy buyinput form-control" id='usdamount' required value='0.00000000' tabindex="1" />
<br/>
How many BRL?
<input onblur='finalAmountUSD()' style='font-size:23px;height:45px' type='number'  class="buy buyinput form-control" id='brlamount' required value='0.00' tabindex="2" />

你的问题是你正试图从

获得价值
 <p id="currentprice" type="number"></p>

代码

x = document.getElementById('currentprice').value;

currentprice是一个p并且没有价值。尝试使用只读输入更改它

还有一个建议:由于金钱价值不是整数,你最好在所有结果上使用parseFloat。另外,我认为你只需要使用onblur事件的使用函数。

答案 1 :(得分:0)

试试这个简单的例子并使用到最后。

<script>
//# <-- access with id
//. <-- access with a class name
var value1 = $("#currentprice").html(); // get values from html object
var value2 = $("#currentprice2").val(); // get values from input
alert("Value: "+value1);
</script>

不要重复ID名称,否则您将有错误。