我正在处理HTML输入字段,我需要允许用户输入数字量。
我需要默认显示0.00,并且当用户输入金额时,例如25,我需要发送值25.00。
我怎样才能做到这一点?
答案 0 :(得分: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>
答案 1 :(得分:2)
var x = 25
var twoDecPlaces = x.toFixed(2)
// returns "25.00"
答案 2 :(得分:1)
这是一个更强角度的js方式的解决方案,限制用户只输入两位小数。
用户输入的小数不能超过两位。并且只有一个小数点
// Code goes here
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.price = 0.00;
$scope.onSubmit = function()
{
alert(parseFloat($scope.price).toFixed(2));
}
});
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>
请运行此代码段。