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
最终结果总结如下(直接查看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)笔记:
在控制台中运行以下代码以了解想法
(30000000).toLocaleString('en-US',{useGrouping:true})
使用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
您可以通过使用伪元素来显示逗号版本来伪造此功能。
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)
看看小提琴