'jquery alert box simple calculation

I want to make simple calculation using js and jQuery. Regarding the values in fields, alertbox should display calculation. Here is my code:

<!DOCTYPE html> 
<html> 
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    </head >
    <body>

        <p id="demo"></p>

        <script>
            $(document).ready(function(){
                $("#btn1").click(function(){
                    alert("Solution: " + $("#demo").val());
                });
            });
            
            function myFunction(a, b) {
                var a;
                var b;
                return a * b;
            }

            document.getElementById("demo").innerHTML = myFunction(a, b);
        </script>

        <input id="a" type="text" value="10" />
        <input id="b" type="text" value="5" />
        <button id="btn1">Result</button>
    </body>
</html>


Solution 1:[1]

Just in case you are particular about using the paragraph element you cannot access the paragraph element by Id but access by tag name instead. Your code can be modified to such for achieving the result:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
  alert("Solution: " + document.getElementsByTagName('p')[0].innerHTML);
});

  document.getElementsByTagName('p')[0].innerHTML = myFunction($('#a').val(), $('#b').val());
});
function myFunction(a, b) {
var a;
var b;
return a * b;
}

</script >
</head>
<body>

  <p id='demo'></p>
  <input type='text' value='10' id='a'>
  <input type='text' value='5' id='b'>
  <button id='btn1'>Result</button>
</body>

Hope this helps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suraj Nair