简体   繁体   English

为什么我的JavaScript表单无法正常工作?

[英]Why doesn't my form with javascript work?

I have a form (im using bootstrap) with 3 number inputs and with the numbers im doing math, this is my code 我有一个带有3个数字输入的表格(我使用引导程序),并且这些数字我正在做数学运算,这是我的代码

 function abc() { var a = document.getElementById("a").value; var b = document.getElementById("b").value; var c = document.getElementById("c").value; var d = Math.pow((b), 2) - (4 * a * c); var x1 = (-b-(Math.sqrt(d))) / (2 * a); var x2 = (-b+(Math.sqrt(d))) / (2 * a); document.write(d); } 
 <div class="row"><!-- Row --> <div class="col-md-4"><!-- Rij links --> <form onsubmit="abc()" role="form"> <div class="form-group"> <label for="a">Vul hier a in:</label> <input type="number" class="form-control" id="a" placeholder="Ax2 + bx + c" > </div> <div class="form-group"> <label for="b">Vul hier b in:</label> <input type="number" class="form-control" id="b" placeholder="ax2 + Bx + c" > </div> <div class="form-group"> <label for="c">Vul hier c in:</label> <input type="number" class="form-control" id="c" placeholder="ax2 + bx + C" > </div> <button type="submit" class="btn btn-default btn-block">Ga!</button> </form> </div><!-- Einde Rij links --> <div class="col-md-4"><!-- Rij rechts --> <p>Je antwoord komt hieronder:</p> <p id="antwoord"></p> </div><!-- Einde Rij rechts --> <div class="col-md-4"> </div> </div><!-- Einde Row --> 

my javascript is right before the closing body tag. 我的javascript就在结束body标签之前。

at first the code worked but than suddenly it stopped working. 最初,代码起作用了,但是突然之间,它停止了工作。 it does nothing 它什么也没做

The onsubmit function is not preventing the page from sending the request back to the server. onsubmit函数不会阻止页面将请求发送回服务器。 Best practice is to return false at the end of the abc function: 最佳做法是在abc函数的结尾处返回false:

 function abc() {
  var a = document.getElementById("a").value;
  var b = document.getElementById("b").value;
  var c = document.getElementById("c").value;
  var d = Math.pow((b), 2) - (4 * a * c);
  var x1 = (-b-(Math.sqrt(d))) / (2 * a);
  var x2 = (-b+(Math.sqrt(d))) / (2 * a);
  document.write(d);

  return false;
}

You should also update the onsubmit as follows: 您还应该如下更新onsubmit:

 <form onsubmit="return abc()" role="form">

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM