在 chrome 中,像
这样的标签<input id="picker" type="date">
呈现为文本字段。然而,调用试图通过类似的东西获得它的值(value)
$("#picker").val()
在输入或从下拉列表中选择有效日期之前不返回任何内容。 我通过按键查看了该对象的所有直接属性
$("#picker").keypress(function() {
var output = ""
for (var i in this) {
output += i +" value:"+ this[i] + "\n";
}
alert(output);
});
但在其中任何一个中都看不到我的输入。在http://jsfiddle.net/5cN2q/自己检查
我的问题是:当输入不是有效日期时,是否可以从 chrome 中的 input[type="date"] 获取文本?
最佳答案
W3C Date State spec定义清理算法:
- The value sanitization algorithm is as follows: If the value of the element is not a valid date string, then set it to the empty string instead.
每当设置输入元素的值时都会调用它,如 DOM input value spec 中定义的那样:
- On getting, it must return the current value of the element. On setting, it must set the element's value to the new value, set the element's dirty value flag to true, invoke the value sanitization algorithm, if the element's type attribute's current state defines one, and then, if the element has a text entry cursor position, should move the text entry cursor position to the end of the text field, unselecting any selected text and resetting the selection direction to none.
因此,当日期无效时,value
属性将始终为空字符串。似乎没有指定“原始/脏/用户键入的文本值”的任何属性,因为它毕竟不是文本输入。
IMO 这是一件好事,它促进了表单验证,因为无效日期被视为虚假值(空字符串),它还让浏览器更自由地实现日期输入的 UI。
如果您更喜欢非 W3C 日期输入,您可以使用具有良好的旧 JS 日期验证和日期选择器的文本输入,例如 jQuery UI datepicker .这将允许您检索输入的实际文本值,并且也是一种更跨浏览器的解决方案。
关于javascript - 从 HTML5 input[type ="date"] in chrome 获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13278016/