jQuery 如何使用 html5 输入类型号处理浮点数和小数点分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15303940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle floats and decimal separators with html5 input type number
提问by devha
Im building web app which is mainly for mobile browsers. Im using input fields with number type, so (most) mobile browsers invokes only number keyboard for better user experience. This web app is mainly used in regions where decimal separator is comma, not dot, so I need to handle both decimal separators.
我正在构建主要用于移动浏览器的网络应用程序。我使用数字类型的输入字段,因此(大多数)移动浏览器仅调用数字键盘以获得更好的用户体验。这个网络应用程序主要用于小数点分隔符是逗号而不是点的区域,所以我需要处理这两个小数点分隔符。
How to cover this whole mess with dot and comma?
如何用点和逗号覆盖整个混乱?
My findings:
我的发现:
Desktop Chrome
桌面版 Chrome
- Input type=number
- User enters "4,55" to input field
$("#my_input").val();
returns "455"- I can not get the correct value from input
- 输入类型=数字
- 用户输入“4,55”到输入字段
$("#my_input").val();
返回“455”- 我无法从输入中获得正确的值
Desktop Firefox
桌面版火狐
- Input type=number
- User enters "4,55" to input field
$("#my_input").val();
returns "4,55"- Thats fine, I can replace comma with dot and get correct float
- 输入类型=数字
- 用户输入“4,55”到输入字段
$("#my_input").val();
返回“4,55”- 没关系,我可以用点替换逗号并获得正确的浮点数
Android browser
安卓浏览器
- Input type=number
- User enters "4,55" to input field
- When input loses focus, value is truncated to "4"
- Confusing to user
- 输入类型=数字
- 用户输入“4,55”到输入字段
- 当输入失去焦点时,值被截断为“4”
- 混淆用户
Windows Phone 8
视窗电话 8
- Input type=number
- User enters "4,55" to input field
$("#my_input").val();
returns "4,55"- Thats fine, I can replace comma with dot and get correct float
- 输入类型=数字
- 用户输入“4,55”到输入字段
$("#my_input").val();
返回“4,55”- 没关系,我可以用点替换逗号并获得正确的浮点数
What are the "best practices" in this kind of situations when user might use comma or dot as decimal separator and I want to keep html input type as number, to provide better user experience?
在这种情况下,当用户可能使用逗号或点作为小数点分隔符并且我想将 html 输入类型保留为数字以提供更好的用户体验时,“最佳实践”是什么?
Can I convert comma to dot "on the fly", binding key events, is it working with number inputs?
我可以将逗号转换为“动态”的点,绑定键事件,它是否适用于数字输入?
EDIT
编辑
Currenlty I do not have any solution, how to get float value (as string or number) from input which type is set to number. If enduser enters "4,55", Chrome returns always "455", Firefox returns "4,55" which is fine.
Currenlty 我没有任何解决方案,如何从类型设置为数字的输入中获取浮点值(作为字符串或数字)。如果最终用户输入“4,55”,Chrome 总是返回“455”,Firefox 返回“4,55”,这很好。
Also it is quite annoying that in Android (tested 4.2 emulator), when I enter "4,55" to input field and change focus to somewhere else, the entered number get truncated to "4".
同样令人讨厌的是,在Android(经过测试的4.2模拟器)中,当我在输入字段中输入“4,55”并将焦点更改为其他位置时,输入的数字会被截断为“4”。
回答by natchiketa
I think what's missing in the answers above is the need to specify a different value for the step
attribute, which has a default value of 1
. If you want the input's validation algorithm to allow floating-point values, specify a step accordingly.
我认为上面的答案中缺少的是需要为step
属性指定不同的值,该属性的默认值为1
. 如果您希望输入的验证算法允许浮点值,请相应地指定一个步骤。
For example, I wanted dollar amounts, so I specified a step like this:
例如,我想要美元金额,所以我指定了这样的步骤:
<input type="number" name="price"
pattern="[0-9]+([\.,][0-9]+)?" step="0.01"
title="This should be a number with up to 2 decimal places.">
There's nothing wrong with using jQuery to retrieve the value, but you will find it useful to use the DOM API directly to get the elements's validity.valid
property.
使用 jQuery 检索值并没有错,但是您会发现直接使用 DOM API 来获取元素的validity.valid
属性很有用。
I had a similar issue with the decimal point, but the reason I realized there was an issue was because of the styling that Twitter Bootstrap adds to a number input with an invalid value.
我对小数点有类似的问题,但我意识到存在问题的原因是 Twitter Bootstrap 添加到具有无效值的数字输入的样式。
Here's a fiddle demonstrating that the adding of the step
attribute makes it work, and also testing whether the current value is valid:
这是一个小提琴,演示添加step
属性使其工作,并测试当前值是否有效:
TL;DR:Set the a step
attribute to a floating-point value, because it defaults to 1
.
TL;DR:将 astep
属性设置为浮点值,因为它默认为1
。
NOTE: The comma doesn't validate for me, but I suspect that if I set my OS language/region settings to somewhere that uses a comma as the decimal separator, it would work. *note in note*: that was not the case for OS language/keyboard settings *German* in Ubuntu/Gnome 14.04.
注意:逗号对我无效,但我怀疑如果我将操作系统语言/区域设置设置为使用逗号作为小数点分隔符的地方,它会起作用。*注意事项*:Ubuntu/Gnome 14.04 中的操作系统语言/键盘设置 *德语* 并非如此。
回答by kjetilh
According to w3.org the valueattribute of the number inputis defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.
根据 w3.org,数字输入的value属性被定义为浮点数。浮点数的语法似乎只接受点作为小数点分隔符。
I've listed a few options below that might be helpful to you:
我在下面列出了一些可能对您有帮助的选项:
1. Using the pattern attribute
1.使用pattern属性
With the patternattribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.
使用pattern属性,您可以以 HTML5 兼容的方式使用正则表达式指定允许的格式。如果模式失败,您可以在此处指定允许使用逗号字符和有用的反馈消息。
<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
Note:Cross-browser support varies a lot. It may be complete, partial or non-existant..
注意:跨浏览器支持差异很大。它可能是完整的、部分的或不存在的。
2. JavaScript validation
2. JavaScript 验证
You could try to bind a simple callback to for example the onchange(and/or blur) event that would either replace the comma or validate all together.
您可以尝试将一个简单的回调绑定到例如onchange(和/或blur)事件,该事件将替换逗号或一起验证。
3. Disable browser validation ##
3.禁用浏览器验证##
Thirdly you could try to use the formnovalidateattribute on the number inputs with the intention of disabling browser validation for that field all together.
第三,您可以尝试在数字输入上使用formnovalidate属性,目的是一起禁用该字段的浏览器验证。
<input type="number" formnovalidate />
4. Combination..?
4. 组合..?
<input type="number" pattern="[0-9]+([,\.][0-9]+)?"
name="my-num" formnovalidate
title="The number input must start with a number and use either comma or a dot as a decimal character."/>
回答by Aeyoun
Whether to use comma or period for the decimal separator is entirely up to the browser. The browser makes it decision based on the locale of the operating system or browser, or some browsers take hints from the website. I made a browser comparison chartshowing how different browsers support handle different localization methods. Safari being the only browser that handle commas and periods interchangeably.
是使用逗号还是句点作为小数点分隔符完全取决于浏览器。浏览器根据操作系统或浏览器的区域设置做出决定,或者某些浏览器从网站获取提示。我制作了一个浏览器对比图,展示了不同浏览器如何支持处理不同的本地化方法。Safari 是唯一可以交替处理逗号和句点的浏览器。
Basically, you as a web author cannot really control this. Some work-arounds involves using two input fields with integers. This allows every user to input the data as yo expect. Its not particular sexy, but it will work in every case for all users.
基本上,您作为网络作者无法真正控制这一点。一些变通方法涉及使用两个带有整数的输入字段。这允许每个用户按预期输入数据。它不是特别性感,但它适用于所有用户的所有情况。
回答by Mike Samuel
Use valueAsNumber
instead of .val()
.
使用valueAsNumber
代替.val()
。
input . valueAsNumber [ = value ]
Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.
输入 。valueAsNumber [ = 值 ]
如果适用,返回表示表单控件值的数字;否则,返回 null。
可以设置,改变值。
如果控件既不是基于日期或时间也不是数字,则抛出 INVALID_STATE_ERR 异常。
回答by Bolo
I have not found a perfect solution but the best I could do was to use type="tel" and disable html5 validation (formnovalidate):
我还没有找到完美的解决方案,但我能做的最好的事情是使用 type="tel" 并禁用 html5 验证 (formnovalidate):
<input name="txtTest" type="tel" value="1,200.00" formnovalidate="formnovalidate" />
If the user puts in a comma it will output with the comma in every modern browser i tried (latest FF, IE, edge, opera, chrome, safari desktop, android chrome).
如果用户输入逗号,它将在我尝试过的每个现代浏览器(最新的 FF、IE、edge、opera、chrome、safari 桌面、android chrome)中以逗号输出。
The main problem is:
主要问题是:
- Mobile users will see their phone keyboard which may be different than the number keyboard.
- Even worse the phone keyboard may not even have a key for a comma.
- 移动用户将看到他们的电话键盘,这可能与数字键盘不同。
- 更糟糕的是,电话键盘甚至可能没有逗号键。
For my use case I only had to:
对于我的用例,我只需要:
- Display the initial value with a comma (firefox strips it out for type=number)
- Not fail html5 validation (if there is a comma)
- Have the field read exactly as input (with a possible comma)
- 用逗号显示初始值(firefox 把它去掉,因为 type=number)
- 不会失败 html5 验证(如果有逗号)
- 将字段完全按照输入读取(可能带有逗号)
If you have a similar requirement this should work for you.
如果您有类似的要求,这应该适合您。
Note:I did not like the support of the pattern attribute. The formnovalidate seems to work much better.
注意:我不喜欢模式属性的支持。formnovalidate 似乎工作得更好。
回答by David Navarro
uses a text type but forces the appearance of the numeric keyboard
使用文本类型但强制显示数字键盘
<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">
the inputmode tag is the solution
inputmode 标签是解决方案
回答by David Navarro
When you call $("#my_input").val();
it returns as string variable. So use parseFloat
and parseInt
for converting.
When you use parseFloat
your desktop or phone ITSELFunderstands the meaning of variable.
当您调用$("#my_input").val();
它时,它会作为字符串变量返回。所以使用parseFloat
和parseInt
进行转换。当您使用parseFloat
台式机或手机时,自己理解变量的含义。
And plus you can convert a float to string by using toFixed
which has an argument the count of digits as below:
此外,您可以通过使用toFixed
其中有一个参数的数字数如下将浮点数转换为字符串:
var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01
回答by stackasec
Sounds like you'd like to use toLocaleString() on your numeric inputs.
听起来您想在数字输入上使用 toLocaleString() 。
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleStringfor its usage.
Localization of numbers in JS is also covered in Internationalization(Number formatting "num.toLocaleString()") not working for chrome
国际化(数字格式“num.toLocaleString()”)中也涵盖了 JS 中数字的本地化不适用于 chrome
回答by Patrick D'appollonio
My recommendation? Don't use jQuery at all. I had the same problem as you. I found that $('#my_input').val()
always return some weird result.
我的推荐?根本不要使用jQuery。我和你有同样的问题。我发现$('#my_input').val()
总是返回一些奇怪的结果。
Try to use document.getElementById('my_input').valueAsNumber
instead of $("#my_input").val();
and then, use Number(your_value_retrieved)
to try to create a Number. If the value is NaN, you know certainly that that's not a number.
尝试使用document.getElementById('my_input').valueAsNumber
而不是$("#my_input").val();
然后,使用Number(your_value_retrieved)
来尝试创建一个数字。如果值为 NaN,您当然知道这不是数字。
One thing to add is when you write a number on the input, the input will actually accept almost any character (I can write the euro sign, a dollar, and all of other special characters), so it is best to retrieve the value using .valueAsNumber
instead of using jQuery.
要添加的一件事是,当您在输入上写一个数字时,输入实际上会接受几乎任何字符(我可以写欧元符号、美元和所有其他特殊字符),因此最好使用.valueAsNumber
而不是使用jQuery。
Oh, and BTW, that allows your users to add internationalization (i.e.: support commas instead of dots to create decimal numbers). Just let the Number()
object to create something for you and it will be decimal-safe, so to speak.
哦,顺便说一句,这允许您的用户添加国际化(即:支持逗号而不是点来创建十进制数)。只要让Number()
对象为你创造一些东西,它就会是十进制安全的,可以这么说。
回答by Joniras
Appearently Browsers still have troubles (although Chrome and Firefox Nightly do fine). I have a hacky approach for the people that really have to use a number field (maybe because of the little arrows that text fields dont have).
显然浏览器仍然有问题(尽管 Chrome 和 Firefox Nightly 做得很好)。对于真正必须使用数字字段的人(可能是因为文本字段没有小箭头),我有一个hacky 方法。
My Solution
我的解决方案
I added a keyup
event Handler to the form input and tracked the state and set the value once it comes valid again.
我keyup
在表单输入中添加了一个事件处理程序并跟踪状态并在它再次有效时设置该值。
Pure JS Snippet JSFIDDLE
纯 JS 代码段 JSFIDDLE
var currentString = '';
var badState = false;
var lastCharacter = null;
document.getElementById("field").addEventListener("keyup",($event) => {
if ($event.target.value && !$event.target.validity.badInput) {
currentString = $event.target.value;
} else if ($event.target.validity.badInput) {
if (badState && lastCharacter && lastCharacter.match(/[\.,]/) && !isNaN(+$event.key)) {
$event.target.value = ((+currentString) + (+$event.key / 10));
badState = false;
} else {
badState = true;
}
}
document.getElementById("number").textContent = $event.target.value;
lastCharacter = $event.key;
});
document.getElementById("field").addEventListener("blur",($event) => {
if (badState) {
$event.target.value = (+currentString);
badState = false;
document.getElementById("number").textContent = $event.target.value;
}
});
#result{
padding: 10px;
background-color: orange;
font-size: 25px;
width: 400px;
margin-top: 10px;
display: inline-block;
}
#field{
padding: 5px;
border-radius: 5px;
border: 1px solid grey;
width: 400px;
}
<input type="number" id="field" keyup="keyUpFunction" step="0.01" placeholder="Field for both comma separators">
<span id="result" >
<span >Current value: </span>
<span id="number"></span>
</span>
Angular 9 Snippet
Angular 9 代码段
@Directive({
selector: '[appFloatHelper]'
})
export class FloatHelperDirective {
private currentString = '';
private badState = false;
private lastCharacter: string = null;
@HostListener("blur", ['$event']) onBlur(event) {
if (this.badState) {
this.model.update.emit((+this.currentString));
this.badState = false;
}
}
constructor(private renderer: Renderer2, private el: ElementRef, private change: ChangeDetectorRef, private zone: NgZone, private model: NgModel) {
this.renderer.listen(this.el.nativeElement, 'keyup', (e: KeyboardEvent) => {
if (el.nativeElement.value && !el.nativeElement.validity.badInput) {
this.currentString = el.nativeElement.value;
} else if (el.nativeElement.validity.badInput) {
if (this.badState && this.lastCharacter && this.lastCharacter.match(/[\.,]/) && !isNaN(+e.key)) {
model.update.emit((+this.currentString) + (+e.key / 10));
el.nativeElement.value = (+this.currentString) + (+e.key / 10);
this.badState = false;
} else {
this.badState = true;
}
}
this.lastCharacter = e.key;
});
}
}
<input type="number" matInput placeholder="Field for both comma separators" appFloatHelper [(ngModel)]="numberModel">