Stop IE11 removing text from input type number

纵饮孤独 提交于 2019-12-10 03:47:10

问题


In Internet Explorer 11, if you have the following:

<input type="number" min="1" max="12" pattern="[0-9]*" >

When a user tries to input letters rather than numbers, the browser just clears the input. This behaviour is undesirable as I want our validation to handle this, rather than the browser automatically doing it for me.

Does anybody know how to change this behaviour?

I'm using the number input type for validation and also to get the correct keyboard in iOS.

JSFiddle demo.


回答1:


Other browsers may keep this text present, however entering "aaa" into an input element whose type attribute is set to "number" will mean that your element's value property is empty, so your validation method would most likely regard this as a lack of content rather than a non-numerical value anyway.

<input type="number" value="aaa" />
console.log(document.querySelector('input').value);
> ""

I've altered your JSFiddle demo to reflect this: http://jsfiddle.net/e1132tg5/3/.

If you need to accept non-numerical data in your input element then the solution is quite simply to change your element's type to "text" instead of "number" and rely solely on your own JavaScript validation methods for handling the validation (as it appears you want anyway).

<input type="text" >

You can always also use your JavaScript to determine whether the user is viewing your site on a mobile device and change the type attribute dynamically.

An alternate solution would be to inform the user that the field must be numerical if the element is blurred with no text present (after IE's automatic removal), but this would be better discussed on SE's UserExperience site.




回答2:


Just use regex instead:

<input type="text" name="amount" id="amount"
    data-val="true"
    data-val-required="Amount field cannot be empty."
    data-val-regex-pattern="^[0-9+.\s]*$"
    data-val-regex="Amount field must be numeric"
    placeholder="Amount">
<span class="field-validation-valid" data-valmsg-for="amount" data-valmsg-replace="true"></span>


来源:https://stackoverflow.com/questions/26255260/stop-ie11-removing-text-from-input-type-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!