HTML5数字输入 - 显示为百分比而不是小数 [英] HTML5 number input - display as percentage instead of decimal

查看:2227
本文介绍了HTML5数字输入 - 显示为百分比而不是小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数字输入的表格,它们应该代表百分比,大致如下所示:

I have a form including number inputs which are supposed to represent percentages, which are set up approximately like below:

<input type="number" min="0" max="1" step="0.01" />

目前,值显示为小数,例如0.25。如果文本字段中显示的数字显示为百分比,我认为它会更加用户友好。我已经使用下面的jQuery代码禁用了字段上的键盘输入,所以我不担心用户输入流氓值:

Currently, the values show up as decimals, for example, 0.25. I think it'd be a lot more user-friendly if the number displayed in the text field showed up as a percentage instead. I've already disabled keyboard input on the field using the below jQuery code, so I'm not worried about users inputting rogue values:

$('input[type="number"]').keypress(function (field) {
    field.preventDefault();
});

是否有一种简单的方法可以更改数字字段以显示百分比?

Is there an easy way to change the number fields to display a percentage?

谢谢!

推荐答案

我希望有两种方法可以使用。

There are two ways which I hope will work.

如果您想要输入百分比并需要将其转换为js中的小数,那么:

If you want percentages in input and need to convert it to decimals in js then:

<input type="number" min="1" max="100" id="myPercent"/>

在js中:

document.getElementById('myForm').onsubmit = function() {
    var valInDecimals = document.getElementById('myPercent').value / 100;
}

如果情况相反,那么:

<input type="number" min="0" max="1" step="0.01" id="myPercent"/>

在js中:

document.getElementById('myForm').onsubmit = function() {
    var valInDecimals = document.getElementById('myPercent').value * 100;
}

这篇关于HTML5数字输入 - 显示为百分比而不是小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆