menu

Questions & Answers

I am trying to make a simple sum function. it,s not working properly. what is wrong?

I am trying to make a simple sum function. it's not working properly. What is wrong?

<head>
    <meta charset="utf-8">
    <title>Calculator using jQuery and Ajax</title>

    <script>
        $(function () {
            $("button").on('click' , function(){
                Add();
                        })
                });
        function Add(){
        var num1 = parseInt($("#num1").val());
        var num2 = parseInt($("#num2").val());
        var result = num1 + num2;
        }
    </script>
</head>

<body>
    <form>
        <input type="number" name="num1" id="num1"> +
        <input type="number" name="num2" id="num2">
        <button type="button" onclick="Add">=</button>
        <div id = "res"></div>

    </form>
</body>

the = button does not show the answer. I don't know what is wrong!!

Comments:
2023-01-23 00:10:06
You never do anything with the result variable
2023-01-23 00:10:06
I am a beginner can you help me?
2023-01-23 00:10:06
How do you expect the button to show the answer?
2023-01-23 00:10:06
Does this answer your question? How can I change div content with JavaScript?
2023-01-23 00:10:06
See second answer for jquery way, but remember that youmightnotneedjquery.com
Answers(2) :

You are getting the sum by var result = num1 + num2; but you are not assigning the variable to <div id="res"></div>.

Try adding this after var result [...]:

$("#res").html(result);
Comments:
2023-01-23 00:10:06
var result = num1 + num2; $("#res").html(variable); It still not working
2023-01-23 00:10:06
Sorry. I meant your variable. So .html(result)

First thing first you haven't import the JQuery library to your code. You can import by simply pasting this to your head tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

Second You haven't sent the result to the output. You can add this

$("#res").html(result); below var result = num1 + num2;