頁面使用模板引擎velocity,要JavaScript實現再一個輸入框中輸入值,另一個輸入框中根據輸入的值來進行計算,得到結果。同時對結果保留兩位小數。
下面是我項目中用的源代碼。
此鏈接是關於該方法的詳細講解
http://www.w3school.com.cn/jsref/jsref_tofixed.asp
<p>#set($path="") ## 標題:創建空交接單 ## @author: zhangbbj ## @time:2016.7.5 //運代交接-新增交接單 按鈕修改 2016.05.05</p> <script type="text/javascript" src="$!{path}/resources/tms/js/consignee.js"></script> <div class="easyui-layout" data-options="fit:true"> <div data-options="region:'north'"> <table class="tms_tool" style="height: 23px; width: 326px;"> <tbody> <tr> <td class="tool_btn_right"><input id="autoPrintFlag" type="checkbox" checked="checked" /><label for="autoPrintFlag">自動打印</label> <a id="add_confirm_btn" href="#">確認</a></td> </tr> </tbody> </table> </div> <div id="add_center" style="padding: 0;" data-options="region:'center',fit:false"><form id="addDispatchPaperForm" method="POST" enctype="multipart/form-data"><input id="jsonData" type="hidden" name="jsonData" /> <input id="autoPrint" type="hidden" name="autoPrint" value="0" /> <input id="add_chargeType" type="hidden" name="chargeType" value="0" /> <table class="table-normal width-99p table-border-1s-gray table-th-center table-td-center table-th-bgcolor-1"> <tbody> <tr id="baoxian4"><th>輸入數字</th> <td><input id="add_insurance_money" style="width: 98%;" type="text" name="insuranceMoney" onchange="countMoneyForInsurance();" /></td> <th>計算結果</th> <td><input id="add_insurance_money_give" style="width: 98%;" type="text" name="insuranceMoneyGive" /></td> </tr> </tr> </tbody> </table> </form></div> </div> <script type="text/javascript" src="$!{path}/resources/jQuery/js/jquery.form.js"></script> <script type="text/javascript">// <![CDATA[ //根據輸入的數字計算出結果並自動填充在輸入框中。 function countMoneyForInsurance() { //方法一使用id選擇器進行計算。 //獲取輸入的數字 var money = $("#add_insurance_money").val(); //自動計算出結果並填充在相應的輸入框中 $("#add_insurance_money_give").val((money*8/10000).toFixed(2)); //方法二使用document進行計算。 // var consigneeName= document.getElementById("add_insurance_money").value; // var countMoney = consigneeName*8/10000; // // document.getElementById("add_insurance_money_give").value = countMoney; } // ]]></script>
這是一個簡單的小例子
<html> <head> <script type="text/javascript"> function displaynum() { var num = new Number(18.86);
var num1 = new Number(18.33); alert(num.toFixed(1));
alert(num1.toFixed(1)); } </script> </head> <body> Show the number 13.37 with one decimal: <form> <input type="button" value="Show!" onclick="displaynum()" > </form> </body> </html>