提交时在文本框中追加编号

时间:2018-07-28 21:00:48

标签: javascript html

提交后,我想在文本框中输入的任何数字上添加两个零。 例如,如果我在文本框中输入34,然后单击“提交”,则应将其另存为3400。

这也可以即时完成吗?

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您总是可以设置一个事件侦听器,该事件侦听器会在form元素退出时更改数字,因此如下所示:

document.addEventListener('DOMContentLoaded', watchNums);

function watchNums() {
    document.removeEventListener('DOMContentLoaded', watchNums);
    
    Array.from(document.getElementsByClassName('number')).map(
        number => {
            number.addEventListener('blur', _ => {
                number.value = parseInt(number.value) * 100;
            })
        }
    )
}
<body>
    <form action="/endpoint.htm" method="POST">
        <input type="number" name="number-input" class="number">
        <input type="number" name="other-number-input" class="number">
        <button type="submit">Submit Numbers</button>
    </form>
</body>

答案 2 :(得分:0)

取决于提交后要执行的操作。特别是:您要将此数字解释为100,然后乘以100(34 * 100),还是要在值后附加一些内容? (“ 34” +“ 00”)?

在第一种情况下,您可以这样做:

<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>


 <script>
  function submit() {
      const input = document.getElementById("value");
      const value = input.attributes.value;

      input.value = parseInt(input.value) * 100;
  }
</script>

在第二种情况下:

<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>

 <script>
  function submit() {
      const input = document.getElementById("value");
      const value = input.attributes.value;

      input.value = input.value.toString() + '00';
  }
</script>