我需要输入保持type="text"
,但会在Android和iOS设备上打开数字键盘。
这是因为输入字段仍会包含£
和,
等字符,这些字符在type="number"
或type="tel"
内无法使用。
我发现您可以使用pattern="\d*"
在iOS上强制使用数字键盘,但这对Android无效。
这是我到目前为止所做的:
<input type="text" inputmode="numeric" pattern="\d*" value="£2,000,000" />
答案 0 :(得分:6)
修改 (如果清除了评论),此答案是在针对移动网络与移动应用指定的问题之前编写的。但是,这个答案将帮助那些在Android上使用WebView时寻找解决方案的人。
在Android上,用于显示页面的WebView可以覆盖onCreateInputConnection。使用此方法,您可以更改imeOptions,但仍限于相同的数字类型。或者,您可以使用creating your own ime type。
一个例子:
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection inputConnection = super.onCreateInputConnection(outAttrs);
outAttrs.inputType = outAttrs.inputType | InputType.TYPE_NUMBER_VARIATION_NORMAL;
return inputConnection;
}
然而,虽然我确信上述内容将解决许多人的问题,但我认为你需要一些更复杂的东西。我的建议是,无论你使用什么键盘类型,都可以使用java来验证和格式化输入,这需要几个步骤:
设置javascript界面
webView.addJavascriptInterface(new ValidationInterface(), "appValidator");
创建界面类
public class ValidationInterface {
//This method would only tell you if a char is invalid
@JavascriptInterface
public boolean isValid(String text){
int len = text.length();
//replace everything thats NOT 0-9, $, £, comma or dot
text = text.replaceAll("[^0-9$£,\.", "");
//Its valid if the length didnt change (because nothing needs removing)
return text.length() == len;
}
//This method would strip out invalid text as you go
@JavascriptInterface
public String getValid(String text){
//replace everything thats NOT 0-9, $, £, comma or dot
return text.replaceAll("[^0-9$£,\.", "");
}
}
文字更改时调用验证
function validate(value) {
//ive not written js in a long time, you'll definitely need to tweak this
//EITHER do this
var valid = appValidator.isValid(value);
if (valid) {
//DO SOEMTHING
} ...
//OR try this
var validText = appValidator.getValid(value);
$('#theField').value(validText); //really not sure this is valid
}
//also just be aware you might need to use keyUp or somethign other than change
//if you are replacing the text as you type, using getValid method
<input id="theField" type="text" onChange="validate(this.value)" ... />
答案 1 :(得分:2)
我正在做类似的事情
查看我的示例:https://jsfiddle.net/pj2uwmtL/6/
$("input.numbers").keypress(function(event) {
return /\d/.test(String.fromCharCode(event.keyCode));
});
答案 2 :(得分:1)
我用:
<input type="text" pattern="\d*" />
没有其他必要。
在iPhone上运行得非常好,尤其是新的键盘类型。使用默认值和Swiftkey。
此外,这适用于所有Android设备。
<强>更新强>
试一试:
<input type="text" step="0.01" pattern="[0-9]*">
<input type="text" min="0" max="100" pattern="[0-9]*">
Or
<input type="text" pattern="\-?\d+(\.\d{0,})?">