使用vanilla JavaScript清除输入框?

时间:2015-05-24 04:50:14

标签: javascript

He Guys,我尝试了几次使用Vanilla javaScript重置我的输入字段但没有成功......我尝试了reset()方法但是,也许我没有正确添加代码......这是我的代码。

   <div class="container">
    <h1>Enter a Number<br />
        from 1 to 100.
    </h1>
    <input type="input" id="inputBox">
    <input type="button" id="button" value="submit" onclick="myFunction()">
    <span id="box1"></span>
   </div>

和js

    function myFunction() {
var i = document.getElementById("inputBox").value;

        //for (var i = 1; i < 100; i++) {

if (i % 3 === 0 && i % 5 === 0) {

    document.getElementById("box1").innerHTML = "fizzbuzz";

} else if (i % 3 === 0) {

    document.getElementById("box1").innerHTML = "fizz";

}   else if (i % 5 === 0) {

    document.getElementById("box1").innerHTML = "buzz";

} else {

    document.getElementById("box1").innerHTML = i;
}


}

我这里也有一支笔: http://codepen.io/lucky500/pen/GJjVEO

谢谢!

1 个答案:

答案 0 :(得分:3)

只需设置输入值document.getElementById("inputBox").value = ""

即可

    function myFunction() {
      var input = document.getElementById("inputBox");
      var i = input.value;

      //for (var i = 1; i < 100; i++) {

      if (i % 3 === 0 && i % 5 === 0) {

        document.getElementById("box1").innerHTML = "fizzbuzz";

      } else if (i % 3 === 0) {

        document.getElementById("box1").innerHTML = "fizz";

      } else if (i % 5 === 0) {

        document.getElementById("box1").innerHTML = "buzz";

      } else {

        document.getElementById("box1").innerHTML = i;
      }

      // clear input

      input.value = "";

    }
<div class="container">
  <h1>Enter a Number<br />
        from 1 to 100.
    </h1>
  <input type="input" id="inputBox">
  <input type="button" id="button" value="submit" onclick="myFunction()">
  <span id="box1"></span>
</div>