✏️ Explanatory Question

jQuery Hands-on 1 Addition

👁 414 Views
📘 Detailed Answer
414
Total Views
4
Related Qs
0%
Progress
No previous question
No next question
💡

Answer with Explanation

1. jQuery Hands-on 1 Addition

Write a function named add() that accepts 2 numbers from users, and returns the sum (integer) of the same.

Get the values of the input fields (IDs #num1 and #num2) from the user, and display the sum in the input field ID #total when the button is clicked.

For invalid inputs, the result should be displayed as 'NaN'.

Sample Code

HTML Code

<html>

<head>
  <link rel="stylesheet" type="text/css" href="style.css">  
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="index.js"></script>
   
</head>
<body>

    <h1>Adding Two Numbers</h1>

<input id="num1" placeholder="0">
<input  id="num2" placeholder="0"></br>


<button id="add" type="button" onclick="add()" >Add</button></br>
<input id="total" placeholder="0" readonly>


    
    
</body>
</html>

Script Code

function add() {
 var num1 = parseInt($("#num1").val());
      var num2 = parseInt($("#num2").val());
      var total = num1 + num2;
      if (isNaN(total)) {
        $("#total").val("NaN");
      } else {
        $("#total").val(total);
      }     

};
No previous question
No next question