将输入限制为数字和。在输入字段 [英] Limit input to numbers and . on input field
问题描述
我收集我没有问正确的问题因为我不知道该怎么做。
所以问题是我有输入元素。保持简单;
< input type =textmaxlength =12name =priceid =price class =foo>
我希望用户只能输入数字,只能输入一个句点(。)价钱。所以可能是3.00或300.00或3000
有人可以帮我解决问题,我会注视眼睛。
老问题在这里快速正则表达式警报
您可以在更改
事件的输入,检查数字格式是否正确。这段代码会尝试获取数字并删除其他任何内容:(假设你使用jQuery,如果没有,请做)
$('#price')。change(function(){
$(this).val($(this).val()。match(/\d*\.?\d+ /));
});
查看工作这里。
编辑:如果你没有jQuery,这段代码也是一样的在Chrome中):
document.getElementById('price')。onchange = function(){
this.value = this.value.match(/\d*\.?\d+/);
};
编辑2 :不确定如果我关注,但可以添加此在更改
事件之前防止字母和其他字符:
$('#price')。keypress(function(event){
var code =(event.keyCode?event.keyCode:event.which);
if(!(
(code> = 48&& code< = 57)//数字
||(code == 46)//句点
)
||( code == 46&& $(this).val()。indexOf('。')!= -1)
)
event.preventDefault();
});
Following on from another question I asked, i really didnt seem to be getting anywhere. Due to my ineptitude. I chose the guys answer because , well he answered my question.
I am gathering I didnt ask the right question cos I have no idea what to do ..
So issue is I have input element . Keeping it simple;
<input type="text" maxlength="12" name="price" id="price" class="foo">
I want users to be able to type in numbers only and only one period ( . ) anywhere in that price. so could be 3.00 or 300.00 or 3000
Could someone please help me out, I am going goggle eyed.
The Older question asked was here Quick regex with alert
You could, in the change
event of the input, check if the number format is OK. This code will try to get the number and remove anything else: (I'm assuming you use jQuery, if not, please do)
$('#price').change(function() {
$(this).val($(this).val().match(/\d*\.?\d+/));
});
See it working here.
EDIT: if you don't have jQuery, this code does the same (at least in Chrome):
document.getElementById('price').onchange = function() {
this.value = this.value.match(/\d*\.?\d+/);
};
EDIT 2: not sure if I follow, but you could add this too to prevent letters and other characters before the change
event:
$('#price').keypress(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
if (!(
(code >= 48 && code <= 57) //numbers
|| (code == 46) //period
)
|| (code == 46 && $(this).val().indexOf('.') != -1)
)
event.preventDefault();
});
这篇关于将输入限制为数字和。在输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!