Javascript HTML5 数字输入 - 显示为百分比而不是小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38041647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:01:13  来源:igfitidea点击:

HTML5 number input - display as percentage instead of decimal

javascriptjqueryhtml

提问by Argus9

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" />

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:

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

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

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

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

Thank you!

谢谢!

回答by Bunny buns

There are two ways which I hope will work.

我希望有两种方法可以奏效。

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

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

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

in js:

在js中:

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

If scenario is reverse then:

如果情况相反,则:

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

in js:

在js中:

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

回答by Tomás Metcalfe

While not a HTML5 input type='number', the solution bellow uses input type='text' to the same effect. The rational of not using type='number' being humans require a nicely formatted string like "23.75%" while robots prefer to read integers and floating points should be avoided. The snippet bellow does just that to 2 decimal places.

虽然不是 HTML5 input type='number',下面的解决方案使用 input type='text' 达到相同的效果。不使用 type='number' 的理由是人类需要一个格式良好的字符串,如“23.75%”,而机器人更喜欢读取整数,应避免使用浮点数。下面的代码段只保留了小数点后两位。

I haven't tested it on a mobile, but I think the number pad should appear as with input type='number'.

我没有在手机上测试过,但我认为数字键盘应该显示为 input type='number'。

Codepen.io: Commented code can be found here

Codepen.io:可以在此处找到注释代码

document.querySelector('.percent').addEventListener('input', function(e) {
  let int = e.target.value.slice(0, e.target.value.length - 1);

  if (int.includes('%')) {
    e.target.value = '%';
  } else if (int.length >= 3 && int.length <= 4 && !int.includes('.')) {
    e.target.value = int.slice(0, 2) + '.' + int.slice(2, 3) + '%';
    e.target.setSelectionRange(4, 4);
  } else if (int.length >= 5 & int.length <= 6) {
    let whole = int.slice(0, 2);
    let fraction = int.slice(3, 5);
    e.target.value = whole + '.' + fraction + '%';
  } else {
    e.target.value = int + '%';
    e.target.setSelectionRange(e.target.value.length - 1, e.target.value.length - 1);
  }
  console.log('For robots: ' + getInt(e.target.value));
});

function getInt(val) {
  let v = parseFloat(val);
  if (v % 1 === 0) {
    return v;
  } else {
    let n = v.toString().split('.').join('');
    return parseInt(n);
  }
}
<input class="percent" type="text" value="23.75%" maxlength="6">

回答by Martijn Ven van de

Maybe add a function, the outputted number (for example 0.25) * 100 + "%", on this way you always have it in percents.

也许添加一个函数,输出的数字(例如 0.25)* 100 + "%",这样你总是以百分比为单位。

function topercentage() {
    var outputnumber = outputnumber * 100 + "%";
}

In this example outputnumber is the number for example 0.25. I hope this works.

在这个例子中 outputnumber 是数字,例如 0.25。我希望这有效。