我需要一个符合以下条件的输入字段,我已经查看了输入掩码,但似乎找不到符合我需要的掩码!任何指针都会非常感激!
该字段用于提交整数货币。我想在用户输入时添加逗号(或者用它来接受正确放置的逗号),例如。 1,000,000,1,000等。
它还需要不允许小数位或自动添加.00到最后。
然后当发布PHP表单时,它只需要发布整个数字(或者结尾的.00就可以了!)。
有人知道我怎么能做到这一点吗?实时验证是最好的,而不是等到提交。 :)
服务器检查格式是否正确,所以不需要担心没有JS提交错误输入的人。
我已经尝试了HTML5数字输入,步骤为1,但这仍然允许我输入小数,甚至提交。我认为这只是为了箭头!
答案 0 :(得分:1)
可以改进。我认为检测用户是否因为错误而按左箭头或右箭头来更改数字并且不在#34; .00"之前重置光标将是一件好事。让他去他想去的地方。
(codepen:https://codepen.io/Alvan/pen/wpjJop)
// Optionnal
$('input').val('.00');
$('input').on('click', function(){
var val = $(this).val();
// If the user hasn't start to fill the input, set the cursor position to 0
if(val.replace('.00', '').length === 0) {
$(this)[0].setSelectionRange(0, 0);
}
});
// Ebd Optionnal
$('input').on('keyup', function(){
var val = $(this).val();
val = val.replace('.00', '') // Replace the ".00" that we automatically add
.toString()
.replace(/\D/g,'') // Replace all that is not a number by nothing
.replace(/,/g, "") // Replace privous comma by nothing
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'.00'; // And here the magic i don't really understand, but comes from a link that i send you ^^.
// Set the new val
$(this).val(val);
// Now we want the cursor to be before the ".00", so we get the length minus the length of ".00", so 3
var strLength = val.length - 3;
// Be sure to focus the input
$(this).focus();
// Set the focus before the ".00"
$(this)[0].setSelectionRange(strLength, strLength);
// And voila !
});

body {
background: #161616;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-family: sans-serif;
}
input {
width: 500px;
height: 50px;
border: 0;
padding: 0 10px;
font-size: 20px;
font-weight: bold;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
&#13;