2014-10-28 42 views
0

我對JS有點新。JavaScript數學運算和輸入到文本字段生活

我試圖帶3個文本字段,並添加它們,然後乘以一個下拉字段與其中的百分比它們的值。一旦完成,我希望它用值填充最終文本字段。

到目前爲止,我還沒有能夠在最終字段中顯示文本,更不用說將它們加在一起。如果有人能幫助我指出正確的方向,我會很感激。

Our Buying Cost: 
<input id="buying_cost" name="buying_cost" type="text" /> 
<br/>Our Shipping Cost: 
<input id="shipping_cost" name="shipping_cost" type="text" /> 
<br/>Our Tax Cost: 
<input id="tax_cost" name="tax_cost" type="text" /> 
<br/>Our Markup: 
<select id="markup" name="markup" value=""> 
    <option value="0">0%</option> 
    <option value="10">10%</option> 
    <option value="20">20%</option> 
    <option value="30">30%</option> 
    <option value="40">40%</option> 
    <option value="50">50%</option> 
    <option value="60">60%</option> 
    <option value="70">70%</option> 
    <option value="80">80%</option> 
    <option value="90">90%</option> 
    <option value="100">100%</option> 
</select> 
<br/> 
<p>New Selling Price:</p> 
<input type="text" id="new_sell_price" name="new_sell_price" value=""> 





$("#buying_cost,#shipping_cost,#tax_cost,#markup).change(function() 
{ 
    var addressArray = [$("#buying_cost").val(), $("#shipping_cost").val(), $("#tax_cost").val(), $("#markup").val()]; 
    $("#new_sell_price").text(addressArray.join(' '));//<--I would like this to be adding all the values 
} 

); 

我在這的jsfiddle

jsfiddle.net/new2programming/hy99yu2m/包括在這裏工作

感謝您的幫助!

+2

你缺少一個「前「).change(函數( )' – ReeCube 2014-10-28 15:44:44

+0

你能再詳細一點,我不確定從哪裏開始? – new2programming 2014-10-28 15:46:52

+1

你在那裏有一個錯字。更改'#markup).change('''#markup「)。更改(' – Populus 2014-10-28 15:48:13

回答

0

這裏一個清潔,簡單的解決方案爲您的問題:on JSFiddle

但要注意,你不應該將此代碼複製粘貼,如果你真的不明白究竟它!

首先,註冊事件:

// I recommend jQuery.on(...) on the document 
$(document).on('input', 'input', calculate); 
$(document).on('change', 'select,input', calculate); 
// use the 'input' event for a live update 
// and the 'change' value for a secure update 

(你可以,如果你想使你的元素的jQuery的選擇替換「輸入」和「選擇,輸入」,讀documentation

在接下來的步驟,您填寫所有你的價值觀陣列:

var values = [ 
    $("#buying_cost").val(), 
    $("#shipping_cost").val(), 
    $("#tax_cost").val(), 
    $("#markup").val() 
]; 

現在,您可以加入所有數組中的值:

var total = eval(values.join('+')); 
// the eval function calculates the given string (generated by the join function) 

而對於最後一步,你設置的計算值:

$("#new_sell_price").val(total); 
// use 'val(...)' and not 'text(...)' because you want to set the value and not the text! 
+0

謝謝你,很好的工作!它強制價值的文本字段,而不是把它放在那裏,並允許我擦除它。讓它在最後一個文本字段中是可刪除的? – new2programming 2014-10-28 18:58:56

+0

將選擇器事件(在on-event中)更改爲可編輯選擇器,或者嘗試以下操作:http://jsfiddle.net/hy99yu2m/7/ – ReeCube 2014-10-29 07:55:46

+0

謝謝!我有一些選擇可以使用 – new2programming 2014-10-29 13:02:27