2016-09-19 67 views
0

我想添加两个已计算和格式化的输入字段,没有太大的运气。我的代码是:使用Javascript添加两个输入框

<input type='text' id='cage_linear_feet' value='83'> 
<input type='text' id='cage_estimate' disabled> 
<br> 
<input type='text' id='cage_doors' value='3'> 
<input type='text' id='doors_estimate' disabled> 
<br> 
<input type='text' id='cage_totals' disabled> 
<script> 
    function format(n) { 
     return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"); 
    } 

    //Linear Feet Calculation 

     $(document).ready(LinearFeet); 
     document.getElementById('cage_linear_feet').addEventListener("keyup", LinearFeet); 

     var inputBox1 = document.getElementById('cage_linear_feet'); 

     function LinearFeet(){ 
     document.getElementById('cage_estimate').value = format(inputBox1.value*225); 
     } 

    //Doors Calculation 

     $(document).ready(CageDoors); 
     document.getElementById('cage_doors').addEventListener("keyup", CageDoors); 

     var inputBox2 = document.getElementById('cage_doors'); 

     function CageDoors(){ 
     document.getElementById('doors_estimate').value = format(inputBox2.value*1800); 
     } 

</script> 

如何实时添加cage_estimatedoors_estimate在一起,并显示在cage_totals

感谢,

约翰

回答

1

这是你问

如何转换逗号分隔的货币成数在Java脚本

parseFloat 

这个函数计算总。你必须在每个关键功能中调用它。

function setTotal(){ 
     var x=document.getElementById('doors_estimate').value; 
     var y=document.getElementById('cage_estimate').value; 

     if(x){ 
     if(y){ 
      var z=(parseFloat(x.replace(',',''))+parseFloat(y.replace(',','')));    
      document.getElementById('cage_totals').value=format(z); 
     } 
     } 
    } 

调用代码

function LinearFeet(){ 
    var inputBox1 = document.getElementById('cage_linear_feet');   
    document.getElementById('cage_estimate').value = format(inputBox1.value*225); 
    setTotal(); 
    } 


    function CageDoors(){ 
    var inputBox2 = document.getElementById('cage_doors');  
    document.getElementById('doors_estimate').value = format(inputBox2.value*1800); 
    setTotal(); 
    } 

Referances:

parseFloat

replace

+0

辉煌!谢谢。我如何让cage_totals以div的形式显示?例如。

+0

@JohnHiggins document.getElementById(“divID”)。innerHTML = format(z); – Sanka

+0

太好了,谢谢Sanka。刚刚解决了它,但是在我接触之前更新了这篇文章!再次感谢。 –