Arg*_*us9 14 javascript jquery html5
我有一个包含数字输入的表单,它应该代表百分比,大致如下所示:
<input type="number" min="0" max="1" step="0.01" />
Run Code Online (Sandbox Code Playgroud)
目前,值显示为小数,例如0.25.如果文本字段中显示的数字显示为百分比,我认为它会更加用户友好.我已经使用下面的jQuery代码禁用了字段上的键盘输入,所以我不担心用户输入流氓值:
$('input[type="number"]').keypress(function (field) {
field.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来更改数字字段以显示百分比?
谢谢!
小智 5
我希望有两种方法可以奏效。
如果您想要输入中的百分比并需要在 js 中将其转换为小数,则:
<input type="number" min="1" max="100" id="myPercent"/>
Run Code Online (Sandbox Code Playgroud)
在js中:
document.getElementById('myForm').onsubmit = function() {
var valInDecimals = document.getElementById('myPercent').value / 100;
}
Run Code Online (Sandbox Code Playgroud)
如果情况相反,则:
<input type="number" min="0" max="1" step="0.01" id="myPercent"/>
Run Code Online (Sandbox Code Playgroud)
在js中:
document.getElementById('myForm').onsubmit = function() {
var valInDecimals = document.getElementById('myPercent').value * 100;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
虽然不是 HTML5 input type='number',但下面的解决方案具有input type='text'相同的效果。不使用人类的理由type='number'需要一个格式良好的字符串,如“23.75%”,而机器人更喜欢读取整数,应避免浮点数。下面的代码片段将其精确到小数点后两位。
我还没有在手机上测试过它,但我认为数字键盘应该显示为input type='number'。
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 == '100'){
e.target.value = int + '%';
e.target.setSelectionRange(3, 3);
} 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);
}
}Run Code Online (Sandbox Code Playgroud)
<input class="percent" type="text" value="23.75%" maxlength="6">Run Code Online (Sandbox Code Playgroud)
小智 0
也许添加一个函数,输出的数字(例如 0.25)* 100 +“%”,这样你就总是以百分比形式得到它。
function topercentage() {
var outputnumber = outputnumber * 100 + "%";
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,outputnumber 是数字,例如 0.25。我希望这能起作用。