HTML输入类型编号千位分隔符

tij*_*ije 32 html javascript html5

我想在我的输入字段中有一千个分隔符(例如1,000,000).但是,它必须是类型编号,因为我需要能够使用"步骤"调整其值.码:

<input type="number" id='myNumber' value="40,000" step='100'>
Run Code Online (Sandbox Code Playgroud)

我尝试使用Javascript来调整值但是没有用.任何帮助,将不胜感激.谢谢!

Ima*_*idi 11

  • 查看此webdesign.tutsplus.com 教程
  • 最终结果总结如下(直接查看Codepen Playground )

    $("#formInput".on("keyup", function(event ) {                   
        // When user select text in the document, also abort.
        var selection = window.getSelection().toString(); 
        if (selection !== '') {
            return; 
        }       
        // When the arrow keys are pressed, abort.
        if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
            return; 
        }       
        var $this = $(this);            
        // Get the value.
        var input = $this.val();            
        input = input.replace(/[\D\s\._\-]+/g, ""); 
        input = input?parseInt(input, 10):0; 
        $this.val(function () {
            return (input === 0)?"":input.toLocaleString("en-US"); 
        }); 
    }); 
    
    Run Code Online (Sandbox Code Playgroud)

笔记:

  • toLocaleString() javascript 函数 实际上显示千位分隔符(示例和文档
  • 在控制台中运行以下代码以了解想法

    (30000000).toLocaleString('en-US',{useGrouping:true})

  • 这太棒了,谢谢。我对其进行了一些修改,以将美元符号保留在文本字段中,并允许向上/向下箭头将值增加和减少 1000。 https://jsfiddle.net/e3czy926/ (2认同)

Haw*_*ett 6

使用autoNumeric插件,您可以使用不同的分隔符将字段作为数字输入。

包括插件:

<script src="~/Scripts/autoNumeric/autoNumeric.min.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

HTML:

 <input type="text" id="DEMO" data-a-sign="" data-a-dec="," data-a-sep="." class="form-control"> 
Run Code Online (Sandbox Code Playgroud)

脚本:

<script>
 jQuery(function($) {
$('#DEMO').autoNumeric('init');   
 });
</script>
Run Code Online (Sandbox Code Playgroud)

您只能输入数字,如果输入100000,99,则会看到100.000,99。

更多:https//github.com/autoNumeric/autoNumeric


jes*_*ssh 2

您可以通过使用伪元素来显示逗号版本来伪造此功能。

div[comma-value]{
  position:relative;
}
div[comma-value]:before{
  content: attr(comma-value);
  position:absolute;
  left:0;
}
div[comma-value] input{
  color:#fff;
}
Run Code Online (Sandbox Code Playgroud)

需要包装 div,因为输入不能有伪元素。

<div>
  <input type="number" id='myNumber' value="40000" step='100'>
</div>
Run Code Online (Sandbox Code Playgroud)

以及一点 JavaScript 来每隔三个字符插入逗号

myNumber.value = commify(myNumber.value)
myNumber.addEventListener("change", function(){
  commify(event.target.value)
})

function commify(value){
  var chars = value.split("").reverse()
  var withCommas = []
  for(var i = 1; i <= chars.length; i++ ){
    withCommas.push(chars[i-1])
    if(i%3==0 && i != chars.length ){  
      withCommas.push(",")
    }
  }
  var val = withCommas.reverse().join("")
  myNumber.parentNode.setAttribute("comma-value",val)
}
Run Code Online (Sandbox Code Playgroud)

看看小提琴

  • 这在 Chrome 中有效,但在 FF 中无效。没有在其他浏览器中尝试过。 (2认同)
  • 您无法编辑该值,如果他们需要小数怎么办 - 这实际上不适用于法国或印度数字 (2认同)