javascript - 提交时在文本框中附加数字
问题描述
我想在提交时向文本框中输入的任何数字添加两个零。例如,如果我在文本框中输入 34 并单击提交,则应将其保存为 3400。
这也可以即时完成吗?
解决方案
有点含糊,但听起来您正在寻找类似以下的内容。
// Gather each element from the HTML, so you can access its input or update its display:
const input = document.getElementById('numberInput');
const button = document.getElementById('submit');
const display1 = document.getElementById('display1');
const display2 = document.getElementById('display2');
// Add a click event to the button, which gathers the text field value, ensures it's a number, and updates the display as requested:
button.addEventListener('click',() => {
const value = input.value;
// This if statement ensures that only numbers will be suffixed with be suffixed with two zeros:
if (isNaN(value)) {
alert('Please enter a valid number');
return;
}
// Update the display span's contents as requested. There are many ways of doing this. Here are a few;
// Here I'm taking the submitted value, and nesting it inside a string, alongside the two zeros. In cases of Infinity or .100, the result will still be the input suffixed with two zeros:
display1.innerHTML = `${value}00`;
// This method, on the other hand, will simply move the decimal to columns:
display2.innerHTML = value * 100;
});
<p>
Display 1: <span id="display1"></span>
</p>
<p>
Display 2: <span id="display2"></span>
</p>
<input type="text" id="numberInput">
<button id="submit">Submit</button>
推荐阅读
- c# - 有没有办法将 HttpGet 方法的参数组合成一个对象?
- powershell - 如何删除权限、成员或角色?
- tensorflow - Tensorflow LSTM 传感器信号平滑
- javascript - Angular 7迭代表
- c# - 我只需要合并gridview中的特定列
- android - Gradle v4 到 Gradle v5 更新 - 每种 JVM 语言的单独输出目录
- c# - 在新对象中通过引用修改静态值变量
- azure - 将 VM-Azure 添加到本地域
- php - 我可以在嵌套的 IF 语句中使用单独的 INSERT 语句将不同的数据添加到两个不同的表中吗?
- android - Firebase:如何获取父节点的父节点?