如何让HTML5号码字段显示尾随零?

Aks*_*hat 23 html5 numbers field input decimal

我有一个领域:

<input type='number' />
Run Code Online (Sandbox Code Playgroud)

我想在0.50没有"纠正它"的情况下打卡0.5,所以它会显示出来0.50.

Nat*_*nes 11

我有一点玩这个,看看规格.它说它必须是一个有效的浮点数.在它给出的有效浮点数定义中有一句话引起了我的注意:

数字n作为浮点数最佳表示是将JavaScript运算符ToString应用于n所获得的字符串.

这意味着格式将始终与评估数字是一致的,然后在该数字上使用JavaScript的toString.所以没有尾随0.

所以,你将不得不求助于JavaScript.这并不简单,因为document.getElementById('numInput').value = '0.50';仍然会得到纠正0.5,因此不会在onchange可以阻止默认操作的位置触发验证,而是在内部触发验证.

这是我能提出的最好的解决方案......这有点像黑客攻击,需要对其进行一些调整以获得稳健性,但希望它能做到你想要的:

var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
    this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
    this.setAttribute('type', 'number');
});
Run Code Online (Sandbox Code Playgroud)

因此,如果用户想要通过键入来输入数字,则会将输入类型切换为文本,但是当他们单击它时,它会将其转换回数字.

如果您总是希望尾随0,无论用户输入什么类型,那么您可以这样做:

var numInput = document.getElementById('numInput');
numInput.addEventListener('blur', function () {
    if (this.value === '') {
        return;
    }
    this.setAttribute('type', 'text');
    if (this.value.indexOf('.') === -1) {
        this.value = this.value + '.00';
    }
    while (this.value.indexOf('.') > this.value.length - 3) {
        this.value = this.value + '0';
    }
});
numInput.addEventListener('focus', function () {
    this.setAttribute('type', 'number');
});
Run Code Online (Sandbox Code Playgroud)

编辑:我认为第二个解决方案更符合用户的期望,但这意味着如果用户输入0.5它将被强制执行0.50,所以这取决于你想要的是什么.

  • 很高兴你喜欢它.这是IMO在HTML5规范中的一个缺点,所以希望有人能够意识到这一点,并在将来的某个时候解决它. (3认同)
  • 这不起作用(至少在 FF 50 中),因为更改“类型”属性会触发模糊。因此,在您的代码中,焦点将类型更改为数字,这会触发模糊,将类型更改为文本,从而触发另一个模糊 - 您永远无法将注意力集中在元素上。 (2认同)

Jac*_*nta 9

我将一个on('change')事件附加到你想要尾随0的输入上

$('.number-input').on('change', function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});
Run Code Online (Sandbox Code Playgroud)

它只需要取值,将其转换为浮点数,将其呈现为字符串为小数位数,然后将其作为值重新放入.

  • 在chrome中工作,但似乎在Firefox中不起作用 (6认同)
  • 对于甚至不存在的问题,这是一个很好的解决方案. (3认同)