我需要千位小数和逗号之后的两位数,如下图所示。
https://brutmaas.net/maas-hesaplama/brutten-nete/tablo
以下代码需要改进。
<input type="number" id="myInput" value="3512.12"
onfocus="focusFunction()"
onblur="blurFunction()" style="text-align: right" />
答案 0 :(得分:0)
您可以使用pattern attribute来限制输入哪些字符(以下限制为数字,点和逗号):
<input type="text" id="num" name="number"
pattern="[0-9.,]+"
onkeypress="return window.validate && validate(event);"
title="Enter german localized number" />
然后使用一些JavaScript来手动或使用globalize.numberParser( [options] )来验证按键事件的格式。
function validate(e) {
var valid = true;
var text = document.getElementById("num").value;
// either manually check if format is valid e.g.
var firstLetter = text.charAt(0);
if(firstLetter === ".") {
valid = false;
}
// etc.
// or parse/validate with globalize
var num = Globalize.numberParser(/*german locale*/)("10.000,00")
valid = !isNaN(parseFloat(num)) && isFinite(num);
return valid;
}
另一种选择可能是让某人进入1234.56
(或其他当地的等价物),然后将其格式化为1.234,56?
答案 1 :(得分:0)
这是一个与您提供的示例页面基本相同的小片段:
// Factory to produce a new number container based on the input value
function createNumericDisplay(input){
var display = document.createElement("div"), decimal = document.createElement("sup"), number = new Number(input.value).toLocaleString('de-DE').split(",");
if(number.length == 1){
number[1] = "0";
}
display.setAttribute("class", "numeric");
display.innerText = number[0];
decimal.innerText = ","+number[1].lpad("0",2).substr(0,2);
display.appendChild(decimal);
return display;
}
// Creates or removes the number
function toggleNumericDisplay(input, show){
var display = input.parentNode.querySelector(".numeric");
if(display && !show){
display.parentNode.removeChild(display);
}else if(!display && show){
display = createNumericDisplay(input);
input.parentNode.appendChild(display);
}
}
// When we focus, remove the formatted number container
function focusFunction(ev) {
toggleNumericDisplay(ev.target, false);
}
// When we blur, create the formatted number container
function blurFunction(ev) {
toggleNumericDisplay(ev.target, true);
}
// Pad a string with zeroes
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
// Initialize values
var numerics = document.body.querySelectorAll(".numeric-wrapper input");
for(var i=0; i<numerics.length; ++i){
toggleNumericDisplay(numerics[i], true);
}
.numeric-wrapper {
display: inline-block;
position: relative;
border: 1px solid #000;
font: 13.3333px "Arial" !important;
}
.numeric-wrapper .numeric {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
pointer-events: none;
background-color: #fff;
text-align: right;
}
.numeric-wrapper .numeric sup {
opacity: 0.75;
}
<div class="numeric-wrapper">
<input type="number" id="myInput" value="1450.91" onfocus="focusFunction(event)" onblur="blurFunction(event)" style="text-align: right" step="1" />
</div>