2016-10-19 16 views
0

嗨,大家好我是新的jquery我創建了一些輸入框,並希望當某人輸入一些值或輸入獲取數據庫的值時,它會自動添加十進制到2我應用此代碼,但它不工作好心幫我在jquery輸入框設置自動小數不起作用

  ?> 
 
     <script type="text/javascript"> 
 
     function setTwoNumberDecimal(event) { 
 
     this.value = parseFloat(this.value).toFixed(2); 
 
      } 
 
     </script> 
 
     <?
print '<tr><td>'; 
 
\t print fieldLabel('Others Deductions','other_deduction',1).'</td><td>'; 
 
\t print '<input class="sub" onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="'.GETPOST("other_deduction").'">'; 
 
\t print '</td></tr>';

回答

1

檢查下面的代碼片段

$(document).ready(function(){ 
 
    $("#text1").bind('change',function(){ 
 
    var value=$(this).val(); 
 
    $(this).val(parseFloat(value).toFixed(2)); 
 
    }) 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="text1" />

希望這有助於

幾點建議

  1. 不要混合使用JavaScript您的標記。嘗試結合您的活動改變/點擊的javascript結束
  2. 在您的setValue方法的代碼,你的傳球事件作爲參數,並試圖訪問THIS.VALUE,這將在這裏指的窗口對象

希望這有助於

+0

它仍然不能正常工作加一兩件事,我在輸入框數據從數據庫中使用JSON和jQuery –

+0

我的代碼也即將工作我只是把功能放在舊的fjquery身上,並且很抱歉,這是一個愚蠢的錯誤 –

0

Everthing是好的,只是使用事件內部功能,而不是這個。

試井目的純HTML代碼和代碼:

function setTwoNumberDecimal(event) { 
 
    event.value = parseFloat(event.value).toFixed(2); 
 
    }
<input type="text class="sub" onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="">

<script type="text/javascript"> 
 
    function setTwoNumberDecimal(event) { 
 
    event.value = parseFloat(event.value).toFixed(2); 
 
    } 
 
    </script>
<?php print '<tr><td>'; 
 
\t print fieldLabel('Others Deductions','other_deduction',1).'</td><td>'; 
 
\t print '<input class="sub" onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="'.GETPOST("other_deduction").'">'; 
 
\t print '</td></tr>'; 
 
?>

0

您的問題是你逝去的對象到您的JavaScript函數(這是正確的),但沒有像你應該使用它。

的代碼應該是這樣的:

 function setTwoNumberDecimal(obj) { 
 
     obj.value = parseFloat(obj.value).toFixed(2); 
 
      }
<tr> 
 
    <td>Others Deductions</td> 
 
    <td> 
 
<input type="text" class="sub" onchange="setTwoNumberDecimal(this)" name="other_deduction" id="other_deduction" size="10" value="" /> 
 
    </td> 
 
</tr>