首页 > 解决方案 > 提交时在文本框中附加数字

问题描述

我想在提交时向文本框中输入的任何数字添加两个零。例如,如果我在文本框中输入 34 并单击提交,则应将其保存为 3400。

这也可以即时完成吗?

标签: javascripthtml

解决方案


有点含糊,但听起来您正在寻找类似以下的内容。

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


推荐阅读