[英]Multiply Dropdown Field to Text Field in 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 。 [注意:您可能必須調整“輸出”(Output)列的大小才能查看下拉列表和文本字段的整個表格。
好的,您超級親密,干得好! 您需要注意的兩件事是這個。
// 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);
使用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中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.