I am using select2. So it is not a real number input field I try to create an input field that allows only numeric with decimal:
<input type="text" name="numeric" class='select2 allownumericwithdecimal'>
$(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^0-9.]/g,''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
What I need now is, that it allows not only point, it should also allow comma. This is my approach:
$(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^0-9.]/g,''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
Still no comma allowed..
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…