首页 > 解决方案 > 接受带逗号和点的小数 (html)

问题描述

我需要一些有关此输入的帮助,因为我希望它只接受 2 个小数和逗号或点,但现在只允许逗号而不是点和任何小数。我对 RegExp 非常陌生,我正在尝试这个。

<td>
    <input type="number" ng-model="material.porcentaje" ng-change="calculaKilos(material, $index);validatePorcentaje($index)" id="porcentaje" class="input_small-stretch" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/">
</td>

标签: javascripthtmlangularjs

解决方案


您不能添加,type="number". 您需要将其更改为type="text",然后onkeyup您可以检查是否有除数字和逗号以外的任何值,您可以将其替换为''

document.querySelector('input').addEventListener('keyup',(e)=>{
	let value = e.target.value;
	e.target.value = value.replace(/[^0-9.,]/g,'');;
})
<input type="text" ng-model="material.porcentaje" ng-change="calculaKilos(material, $index);validatePorcentaje($index)" id="porcentaje" class="input_small-stretch" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/">

希望它会有所帮助


推荐阅读