带有输入模式的 Javascript 数字和逗号

Javascript Numbers and Comma with input pattern

本文关键字:数字 Javascript 输入模式      更新时间:2023-09-26

嗨,我需要结合 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>