2013-06-04 40 views
0

我遇到以下問題:使用可更改的輸入字段計算

當以下輸入中的值發生更改時,字段#result應該更改。

<input type="text" data-original-value="320" value="320" name="value1" id="value1" class="restorable"> 
<input type="text" data-original-value="125" value="125" name="value2" id="value2" class="restorable"> 
<input type="text" data-original-value="0.5" value="0.5" name="value3" id="value3" class="restorable"> 


    (function ($) { 
    $(document).ready(function() { 
     $('#coverage').keyup(function() { 
      var raw = $('#value1').text()-($('#value2').text()* $('#value3').text()); 
      var fixed = raw.toFixed(); 
      $('#result').text(fixed); 
     }); 
    }); 
}(jQuery)); 

將其改爲1倍時的值,而是如何使它可能

  • #result計算時,頁面加載
  • #result更新值1或值2和值3的變化時工作
+0

目前,'$('。value2')''和'$('。value3')'選擇器不會匹配您發佈的任何內容。 – Jasen

+0

你爲什麼要這樣做?你刷新頁面,這些字段將是空的不會他們?那麼計算的用途是什麼?還是有'ajax'調用發生在'ready'上,你沒有發佈? – krishgopinath

+0

@Jasen我拼錯它應該是#value2,... – jimi

回答

0

您需要創建一個執行計算的jQuery函數,然後將事件偵聽器附加到每個字段中:

$('#value1, #value2, #value3').on('keyup', function() { 
    calculate(); 
}); 

var calculate = function() { 
    var result = $('#value1').val() - ($('#value2').val() * $('#value3').val()); 
    $('#result').text(result.toFixed(2)); 
}; 

我會重新因素這雖然,通過增加普通類或數據屬性來識別它們作爲你的計算的一部分,你的HTML元素,這樣你就不會在有硬編碼的引用您的jQuery腳本。

您還需要添加用戶實際將數字輸入到輸入中的驗證。

+1

完成,您可以將'calculate'傳遞給事件處理程序,而不將其包裝在函數中: )'$('#value1,#value2,#value3')。on('keyup',calculate)' – krishgopinath

+1

是的,你可以這樣做。深夜的問題回答:) –

2

我建議:

// bind the 'keyup' event to the elements: 
$('input.restorable').keyup(function(){ 
    // set the text of the '#result' element: 
    $('#result').text(function(){ 
     // initialise a variable to hold the value: 
     var total = 0; 
     // get the relevant sibling 'input' elements, and iterate over them: 
     $(this).siblings('input.restorable').each(function(){ 
      /* add the value, using parseFloat() to make it a numeric value, 
       to that total variable: */ 
      total += parseFloat(this.value); 
     }) 
     // set the text to the value of that variable 
     return total; 
    }); 
// trigger the function bound on 'keyup' by triggering a 'keyup' event: 
}).trigger('keyup'); 

JS Fiddle demo

參考文獻: