2016-09-19 134 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。剛剛解決了它,但是在我接觸之前更新了這篇文章!再次感謝。 –

相關問題