Html 如何获取 <input type="number"> 字段的原始值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18852244/
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 get the raw value an <input type="number"> field?
提问by Ian Boyd
How can i get the "real"value of an <input type="number">
field?
如何获得字段的“真实”值<input type="number">
?
I have an input
box, and i'm using newer HTML5 input type number
:
我有一个input
盒子,我使用的是较新的 HTML5 输入类型number
:
<input id="edQuantity" type="number">
This is mostly supported in Chrome 29:
这在 Chrome 29 中主要受支持:
What i now need is the ability to read the "raw"value the user has entered in the input box. If the user has entered a number:
我现在需要的是能够读取用户在输入框中输入的“原始”值。如果用户输入了一个数字:
then edQuantity.value = 4
, and all is well.
然后edQuantity.value = 4
,一切都很好。
But if the user enters invalid text, i want to color the input-box red:
但是如果用户输入无效文本,我想将输入框着色为红色:
Unfortunately, for a type="number"
input box, if the value in the text-box is not a number then value
returns an empty string:
不幸的是,对于type="number"
输入框,如果文本框中的值不是数字,则value
返回一个空字符串:
edQuantity.value = "" (String);
(in Chrome 29 at least)
(至少在 Chrome 29 中)
How can i get the "raw"value of an <input type="number">
control?
如何获得控件的“原始”值<input type="number">
?
i tried looking through Chrome's list of other properties of the input box:
我尝试查看 Chrome 的输入框其他属性列表:
i didn't see anything that resembles the actual input.
我没有看到任何类似于实际输入的内容。
Nor could i find a way to tell if the box "is empty", or not. Maybe i could have inferred:
我也找不到一种方法来判断盒子是否“为空”。也许我可以推断:
value isEmpty Conclusion
============= ============= ================
"4" false valid number
"" true empty box; not a problem
"" false invalid text; color it red
Note: You can ignore everything after the horizontal rule; it's just filler to justify the question. Also: don't confuse the example with the question. People might want the answer to this question for reasons otherthan coloring the box red (One example: converting the text "four"
into the latin "4"
symbol during the onBlur event)
注意:横线之后的所有内容都可以忽略;这只是证明问题的填充物。另外:不要将示例与问题混淆。人们可能要回答这个问题的原因其他比着色盒红(一个例子:将文本转换"four"
成拉丁"4"
onblur事件中的符号)
How can i get the "raw"value of an <input type="number">
control?
如何获得控件的“原始”值<input type="number">
?
Bonus Reading
奖励阅读
采纳答案by j08691
According to the WHATWG, you shouldn't be able to get the value unless it's valid numeric input. The input number field's sanitization algorithm says the browser is supposed to set the value to an empty string if the input isn't a valid floating point number.
根据WHATWG,除非它是有效的数字输入,否则您应该无法获得该值。输入数字字段的清理算法表明,如果输入不是有效的浮点数,浏览器应该将该值设置为空字符串。
The value sanitization algorithmis as follows: If the valueof the element is not a valid floating-point number, then set it to the empty string instead.
By specifying the type (<input type="number">
) you're asking the browser to do some work for you. If, on the other hand, you'd like to be able to capture the non-numeric input and do something with it, you'd have to rely on the old tried and true text input field and parse the content yourself.
通过指定类型 ( <input type="number">
),您是在要求浏览器为您做一些工作。另一方面,如果您希望能够捕获非数字输入并对其进行处理,则必须依靠旧的、经过验证的真实文本输入字段并自己解析内容。
The W3also has the same specs and adds:
在W3还具有相同的规格,并增加了:
User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number.
用户代理不得允许用户将值设置为不是有效浮点数的非空字符串。
回答by Ian Boyd
It doesn't answer the question, but the useful workaround is to check
它没有回答问题,但有用的解决方法是检查
edQuantity.validity.valid
The ValidityState
of an object gives clues about what the user entered. Consider a type="number"
input with a min
and max
set
该ValidityState
对象给出关于用户输入的内容线索。考虑type="number"
带有 amin
和max
set的输入
<input type="number" min="1" max="10">
We alwayswant to use .validity.valid
.
我们总是想使用.validity.valid
.
Other properties only give bonus information:
其他属性仅提供奖励信息:
User's Input .value .valid | .badInput .rangeUnderflow .rangeOverflow
============ ====== ====== | ========= =============== ==============
"" "" true | false false false ;valid because field not marked required
"1" "1" true | false false false
"10" "10" true | false false false
"0" "0" false | false true false ;invalid because below min
"11" "11" false | false false true ;invalid because above max
"q" "" false | true false false ;invalid because not number
"3" "" false | true false false ;superscript digit 3
"?" "" false | true false false ;arabic digit 3
"?" "" false | true false false ;subscript digit 3
You'll have to ensure that the the browser supports HTML5 validation before using it:
在使用之前,您必须确保浏览器支持 HTML5 验证:
function ValidateElementAsNumber(element)
{
//Public Domain: no attribution required.
if ((element.validity) && (!element.validity.valid))
{
//if html5 validation says it's bad: it's bad
return false;
}
//Fallback to browsers that don't yet support html5 input validation
//Or we maybe want to perform additional validations
var value = StrToInt(element.value);
if (value != null)
return true;
else
return false;
}
Bonus
奖金
Spudly has a useful answer that he deleted:
Spudly 删除了一个有用的答案:
Just use the CSS
:invalid
selector for this.input[type=number]:invalid { background-color: #FFCCCC; }
This will trigger your element to turn red whenever a non-numeric valid is entered.
Browser support for
<input type='number'>
is about the same as:invalid
, so no problem there.
只需
:invalid
为此使用 CSS选择器。input[type=number]:invalid { background-color: #FFCCCC; }
每当输入非数字有效值时,这将触发您的元素变为红色。
浏览器对 的支持与
<input type='number'>
大致相同:invalid
,因此没有问题。
回答by int32_t
input.focus();
document.execCommand("SelectAll");
var displayValue = window.getSelection().toString();
回答by sandstrom
Track all pressed keys based on their key codes
根据按键代码跟踪所有按下的按键
I suppose one could listen to the keyup events and keep an array of all characters entered, based on their keycodes. But it's a pretty tedious task and probably prone to bugs.
我想人们可以监听 keyup 事件并根据他们的键码保留输入的所有字符的数组。但这是一项非常乏味的任务,并且可能容易出现错误。
http://unixpapa.com/js/key.html
http://unixpapa.com/js/key.html
Select the input and get the selection as a string
选择输入并将选择作为字符串获取
document.querySelector('input').addEventListener('input', onInput);
function onInput(){
this.select();
console.log( window.getSelection().toString() )
}
<input type='number'>
All credit to: int32_t
全部归功于:int32_t