使用html和javascript添加两个数字

时间:2016-06-15 07:02:43

标签: javascript html

我正在尝试添加两个数字。从用户那里获取输入但我无法找到我出错的地方。每次我点击提交它都只刷新页面。

<!--Html -->



     <html>
        <body>
            <div class="container-fluid">
                <header>
                    <h1>Business Registration Address Setup</h1>
                </header>

         <form>
                <label>number 1</label>
                <input type="text" name="number1" id="number1" placeholder="enter single digit number"> <br>
                +<br>
                <label>number 2</label>
                <input type="text" name="number2" id="number2" placeholder="enter single digit number"><br>
                <button type="submit" class="btn btn-info" onclick="submit1()">submit</button><br><br>
                <div class="screen" id="screen1"></div>

            </form>

            </div> <!-- End Container-->



        <footer>

        </footer>
          <script type="text/javascript">
              function submit1(){
                 var a = document.getElementByID("number1").value;
              var b = document.getElementByID("number2").value;
                var c = a + b; 
            document.getElementByID("screen1").innerHTML=c;
              }
          </script>

        </body>
        </html>

2 个答案:

答案 0 :(得分:1)

您正在使用type="submit"了解页面刷新的原因。

点击type="button"时,您需要使用javascript function来呼叫button

<button type="button" class="btn btn-info" onclick="submit1()">submit</button><br><br>

此外,您使用的document.getElementByID不是document.getElementById的函数。

您还需要parseint的值added设为concatenated,否则值只有added而不是var c = parseInt(a) + parseInt(b);

{{1}}

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<body>

<div class="container-fluid">
    <header>
        <h1>Business Registration Address Setup</h1>
    </header>

    <label>number 1</label>
    <input type="text" name="number1" id="number1" placeholder="enter single digit number"> <br>
    +<br>
    <label>number 2</label>
    <input type="text" name="number2" id="number2" placeholder="enter single digit number"><br>
    <button type="button" class="btn btn-info" onclick="submit1()">submit</button><br><br>
    <div class="screen" id="screen1"></div>


</div> <!-- End Container-->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {

});
function submit1(){
    var a =  document.getElementById("number1").value;
    var b =  document.getElementById("number2").value;
    var c = parseInt(a) + parseInt(b); 
    document.getElementById("screen1").innerHTML=c;
  }
</script>

</body>
</html>

修改

document.getElementByID  -------> document.getElementById
var c=a+b ----------------------> var c = parseInt(a) + parseInt(b)
button type="submit" -----------> button type="button"