2014-04-30 54 views
0

嘗試使用下拉菜單和數量創建各種計算器。如何將下拉式的值與文本字段相乘,並使用Javascript將結果顯示在另一個文本字段中?這將適用於表格中的每一行。將下拉字段與JavaScript中的文本字段相乘

HTML:

<table width="594" border="1"> 
    <tr> 
    <th colspan="2" scope="col"><strong>Line Breakdown</strong></th> 
    <th colspan="2" scope="col"><strong>Qty</strong></th> 
    <th width="90" scope="col">Unit Line Cost</th> 
    <th width="90" scope="col">Total Line Cost</th> 
    </tr> 
    <tr> 
    <td width="122"><strong>Cabinets</strong></td> 
    <td width="150"><select name="DDcabinets" id="DDcabinets"> 
     <option value="">Select an option …</option> 
     <option value="100">Dura Supreme</option> 
     <option value="110">Lenape Village</option> 
     <option value="120">Wellborn Forest</option> 
    </select></td> 
    <td width="65"><input type="text" name="Qcabinets" id="Qcabinets" size="10" maxlength="5"/></td> 
    <td width="41">ft.</td> 

的Javascript:

window.onload = function() { 
     var select1 = document.getElementById('DDcabinets'); 
     var input1 = document.getElementById('Vcabinets'); 
     select1.onchange = function() { 
      input1.value = select1.value; 
     }; 

我加入此Javascript,但它不工作 - 我猜我的JavaScript數學有點過(這一點,我只是真的不熟悉編碼。)

 var total1 = document.getElementById('Tcabinets'); 
     var qty1 = document.getElementsById('Qcabinets'); 
     qty1.onchange = function() { 
      total1.value = select1.value * qty1.value; 
     };   

另請參閱http://jsbin.com/dodew/2/edit的完整腳本。 [注意:您可能需要調整「輸出」列的大小以查看整個下拉列表和文本框的表格。]

+0

裏面你真的有意使用jQuery?沒有,只需要澄清就可以輕鬆完成。另外,你有一個錯字'var qty1 = document.getElementsById('Qcabinets');','document.getElementById()'中沒有's'。 –

回答

1

好吧,讓您超級密切,出色!你需要注意的兩件事是這樣的。

// getElement(s)ById, no such thing! Change it to getElementById 
var qty1 = document.getElementsById('Qcabinets'); 

接下來的事情,就是值存儲爲string的元素,你需要將它們轉換爲整數值,我傾向於parseFloat要做到這一點,但parseInt函數是一樣好選擇。

只是改變你的乘法將字符串轉換爲積分,你很好!

total1.value = parseFloat(select1.value) * parseFloat(qty1.value); 
+0

完美!謝謝! – user3587300

0

使用jQuery:

$('#DDcabinets').change(function(){ 

      $('#Vcabinets').val($('#DDcabinets').val()) ; 
     }); 

    $('#Qcabinets').change(function(){ 

      $('#Tcabinets').val($('#Vcabinets').val()*    $('#Qcabinets').val()); 
     }); 

$('#DDcountertop').change(function(){ 

      $('#Vcountertop').val($('#DDcountertop').val()) ; 
     }); 

    $('#Qcountertops').change(function(){ 

      $('#Tcountertops').val($('#Vcountertop').val()*    $('#Qcountertops').val()); 
     }); 

將這個代碼的document.ready

Demo