表单简单的网页会在表单提交时重新加载

时间:2019-02-27 08:15:16

标签: javascript html html5

我有一个简单的HTML表单,并且正在使用JavaScript将输入的值显示到网页上,但是每次我点击“提交”都会重新加载网页。

我已经阅读了Webpage reloading on submitting form上的问题,但这是jQuery,而e.preventDefault();在我的情况下不起作用。 如何阻止页面重新加载?

我有以下代码:

function myFunction() {
  var pm1, sqrtInt, pm2, constInt;

  pm1 = document.getElementById("pm1").value;
  pm1 = document.getElementById("sqrtInt").value;
  pm1 = document.getElementById("pm2").value;
  pm1 = document.getElementById("constInt").value;

  document.getElementById("proof").innerHTML = 
      '<br>pm1 = ' + pm1 + 
      '<br>sqrtInt = ' + sqrtInt + 
      '<br>pm2 = ' + pm2 + 
      '<br>constInt = ' + constInt;
}
#proof {
  background: black;
  color: yellow;
  width: 100%;
  height: 20%;
}
<div>Form Trial</div>
<div>
  <form onsubmit="myFunction()">
    <div>
      <select class="uk-select" id="pm1">
        <option>Minus (-)</option>
        <option>Plus (+)</option>
      </select>
    </div>
    <div>
      <input class="uk-input" type="text" placeholder="Square Root" id='sqrtInt'>
    </div>
    <div>
      <select id="pm2">
        <option>Minus (-)</option>
        <option>Plus (+)</option>
      </select>
    </div>
    <div>
      <input type="text" placeholder="Constant" id='constInt'>
    </div>
    <div>
      <input type="submit" value='submit'>
    </div>
  </form>
</div><br><br>
<div id="proof"></div>

1 个答案:

答案 0 :(得分:3)

要做两件事:

  1. return代码中添加onsubmit

    <form onsubmit="return myFunction()">
    
  2. myFunction函数的末尾添加:

    return false;
    

function myFunction() {
  var pm1, sqrtInt, pm2, constInt;

  pm1 = document.getElementById("pm1").value;
  pm1 = document.getElementById("sqrtInt").value;
  pm1 = document.getElementById("pm2").value;
  pm1 = document.getElementById("constInt").value;

  document.getElementById("proof").innerHTML = 
      '<br>pm1 = ' + pm1 + 
      '<br>sqrtInt = ' + sqrtInt + 
      '<br>pm2 = ' + pm2 + 
      '<br>constInt = ' + constInt;
  return false; // <---------
}
#proof {
  background: black;
  color: yellow;
  width: 100%;
  height: 20%;
}
<div>Form Trial</div>
<div>
  <form onsubmit="return myFunction()">
    <div>
      <select class="uk-select" id="pm1">
        <option>Minus (-)</option>
        <option>Plus (+)</option>
      </select>
    </div>
    <div>
      <input class="uk-input" type="text" placeholder="Square Root" id='sqrtInt'>
    </div>
    <div>
      <select id="pm2">
        <option>Minus (-)</option>
        <option>Plus (+)</option>
      </select>
    </div>
    <div>
      <input type="text" placeholder="Constant" id='constInt'>
    </div>
    <div>
      <input type="submit" value='submit'>
    </div>
  </form>
</div><br><br>
<div id="proof"></div>