jQuery Hands-on 1 Addition

jQuery >   jQuery Tutorial >   jQuery Tutorial  

Long Question

465


Answer:

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);
      }     

};


This Particular section is dedicated to Question & Answer only. If you want learn more about jQuery. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.