2016-11-30 99 views
1

我正在处理HTML输入字段,我需要允许用户输入数字量。如何在金额字段中添加十进制数字。 (0.00)

默认情况下,我需要显示0.00,并且当用户输入金额时,例如, 25,我需要发送价值25.00。

我该如何做到这一点?

+3

检查出号'toFixed()'方法:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed –

+3

可能重复[在JavaScript中格式化数字,精确到两位小数](http://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – anu

+0

我删除了角度js标记因为没有代码提及它。请添加相关代码,然后添加角度js标签。谢谢。 – Sid

回答

3

$(".click").on('click', function() { 
 
    var val = $(".decimalInput").val(); 
 
    var decVal = parseFloat(val).toFixed(2); 
 
    $(".decimalInput").val(decVal) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<input value=0.00 class='decimalInput'> 
 
<button class='click'> 
 
    Click! 
 
</button>

+0

它需要多个小数我需要只允许一个。 – User123

+0

你是什么意思,你只需要一个?只有一个输入? – philantrovert

1

下面是在更角JS方式溶液,限制用户输入只有两个小数

用户不能输入两位以上的小数。也只有一个小数点

// Code goes here 
 

 
var app = angular.module('myApp', []); 
 
app.controller('formCtrl', function($scope) { 
 
    $scope.price = 0.00; 
 
\t $scope.onSubmit = function() 
 
\t { 
 
\t 
 
\t \t alert(parseFloat($scope.price).toFixed(2)); 
 
\t } 
 
}); 
 
app.directive("validateWith", [function(){ 
 
    return { 
 
     restrict: "A", 
 
     link: function($scope, $el, $attrs){ 
 
      var regexp = eval($attrs.validateWith); 
 
      var origVal; 
 
      // store the current value as it was before the change was made 
 
      $el.on("keypress", function(e){ 
 
       origVal = $el.val(); 
 
      }); 
 

 
      // after the change is made, validate the new value 
 
      // if invalid, just change it back to the original 
 
      $el.on("input", function(e){ 
 
       console.log(regexp.test($el.val())) 
 
       if(!regexp.test($el.val())){ 
 
        e.preventDefault(); 
 
        $el.val(origVal); 
 
       } 
 
       
 
      }); 
 
     } 
 
    } 
 
}]);
<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    <link rel="stylesheet" href="style.css"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> 
 
    <script src="script.js"></script> 
 
    </head> 
 

 
    <body> 
 
<div ng-app="myApp" ng-controller="formCtrl"> 
 
<form name="myForm" ng-submit="onSubmit()"> 
 
    <input type="number" ng-model="price" name="price_field" required validate-with="/^\d{1,5}(\.\d{1,2})?$/" step="0.01" value="0.00"/> 
 
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span> 
 
    <input type="submit" value="submit"/> 
 
</form> 
 
</div> 
 
    </body> 
 

 
</html>

请运行该代码段。

Here is a Working demo

相关问题