我有一个 JQuery 语法,允许用户在文本字段中只输入数字。 Live code
然后我需要写一个额外的代码来让用户可以在文本框中输入“-”(连字符),但它不起作用。 Live code
请帮忙。
HTML
Number : <input type="text" name="quantity" id="quantity" /> <span id="errmsg"></span>
CSS
#errmsg{color: red;}
JS
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && e.which !=='-' && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
最佳答案
您可以通过在您的条件中添加 String.fromCharCode(e.which) != '-'
(-
的字符代码)来允许连字符:
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != '-' && (e.which < 48 || e.which > 57)) {
...
}
关于javascript - 使用 jquery 在文本框中仅输入数字和 "-",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049958/