[javascript][jquery]限定textbox只能輸入數字
textbox的html:
<input type="text" class="form-control" id="txtAchieveStartDate" value="" onkeypress="return isNumber(event,'txtAchieveStartDate')" placeholder="格式YYYMM 202201">
javascript:
function isNumber(evt, objId) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if ($('#' + objId).val().length >= 6) {
return false;
}
return true;
}
這篇大概是這樣~
ps.20230505補充:以下寫法可限定textbox只可以輸入浮點數
html + javascript:
<script type="text/javascript" >
$(document).ready(function () {
//float number only
$('input.float').on('input', function () {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
});
});
</script>
<input type="text" class="form-control float" id="txtWeightKG" value="50" placeholder="請輸入數字">
參考資料:
工作經驗
allowing input only for float number
https://stackoverflow.com/questions/10150877/allowing-input-only-for-float-number