带有输入模式的 Javascript 数字和逗号
Javascript Numbers and Comma with input pattern
嗨,我需要结合 2 个错误检查程序。我不使用 jquery我只希望这些值出现在0123456789,
我的 HTML,我需要知道我网站其他实例的模式
<input type="text" pattern="?" maxlength="10" id="f2f11c3" value="0"></input>
我的简斯
document.getElementById("f2f11c3").addEventListener("keyup", function(){addcommas("f2f11c3")}, false);
.
function addcommas(id)
{
//i dont know what to place here
//every 3 numbers must have a comma
//ie. input is 123.c39,1mc
//it must also remove if a comma is placed manually
//result must be 123,391
}
希望有人能帮忙。谢谢!
document.getElementById('f2f11c3').
addEventListener("input", function(){addcommas();}, false);
function addcommas()
{
var v = document.getElementById('f2f11c3');
var t = v.value.replace(/'D/g, '');
var i,temp='';
for(i=t.length; i>=0;i-=3){
if(i==t.length) {
temp=t.substring(i-3,i);
}
else
{
if(t.substring(i-3,i)!="")
temp = t.substring(i-3,i)+','+temp;
}
if(i<0) {temp=t.substring(0,i+3)+','+temp; break;}
}
v.value = temp;
}
演示
function addcommas(id) {
var arr = [];
// loop over the id pushing numbers into the array
for (var i = 0, l = id.length; i < l; i++) {
if (id[i] >= 0 && id[i] <= 9) {
arr.push(id[i]);
}
}
// loop over the array splicing in commas at every 3rd position
for (var i = 0, l = arr.length; i < l; i += 3) {
arr.splice(i, 0, ',');
i++;
l++;
}
// remove the first unnecessary comma
arr.shift()
// return the comma-separated string
return arr.join('');
}
演示
id
是 HTML 元素的 id,而不是值
function addcommas(id)
{
//Not really needed, but just to shorten the details below
var x = document.getElementById(id);
//Current value but removes anything aside from numbers 0-9 and comma (not really needed)
var curval = x.value.replace(/[^'d,]/g,'');
//Strips the comma from the current value if someone entered it manually.
var nocomma = x.value.replace(/[^'d]/g,'');
//If not blank, prevent NAN error
if (nocomma.length>0)
{
//Converts text to int
nocomma = parseInt(nocomma, 10);
//Dont know why, but doesnt work without this
nocomma = nocomma+0;
//Converts it back to string to add the comma
nocomma = nocomma+"";
//Adds comma every 3 numbers, I got this from other research, dont know how it works
x.value = nocomma.replace(/('d)(?=('d{3})+$)/g, '$1,');
}
}
我在 HTML 中的输入如下
//for iphone, this will popout the numberpad with choices 0-9 only. Easier to type, better mobile usability.
<input type="text" pattern="'d*" maxlength="12" id="f2f11c3" value="0"></input>
相关文章:
- 使用全局变量来存储数字(JavaScript)
- 字符串到数字JavaScript
- 查找总和最大的数字(Javascript)
- 将字符串中的重复字符替换为不断增长的数字 [Javascript]
- 选择下拉选项时显示数字-javascript
- 用户在数字上输入金额,然后输出最高数字javascript
- 字母数字 JavaScript 正则表达式失败
- 仅数字 Javascript 表单验证
- 如何从一组特定的数字中找到最接近的更高数字:javascript
- 将字符串 num 转换为数字 JavaScript
- 将字符串转换为数字 Javascript
- 提取两种模式之间的数字 javascript
- 添加两个十六进制数字 javascript 与位移
- 确定是否按下了字母或数字-Javascript
- 可以't将字符串转换为数字javascript我的代码出了什么问题
- 按布尔值,然后按数字(javascript)对对象数组进行排序
- 正则表达式,用于获取方括号之间的字符串和数字-javascript
- If和Else比较数字JavaScript
- 检查变量是网页上的所有数字javascript
- 同时检查模为0的两个不同数字(Javascript)