javascripthtmlinnerhtmlweb-developer-toolbar

why innerHTML is not able to set the value of id = 'result' field to show the interest ..?


[i am not able to get the desired output of getting the simple interest....here innerhtml is not responding to set the value of id = 'result' field......here i have posted my code part..

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Document</title>
<script type="text/javascript">
    function fun1()
    {
      var a = document.getElementById('p').value ;
      var b = document.getElementById('n').value ;
      var c = document.getElementById('r').value ;
      var result = document.getElementById('result');

      result.innerHTML = "The interest is" + (p*n*r/100) ;
    }
</script>
</head>
<body>

<form name="form1">
    <label> Enter Principal amount :
        <input type="text" id="p"><br>
    </label>

    <label> Enter no. of years :
        <input type="text" id="n"><br>
    </label>

    <label> Enter rate  :
        <input type="text" id="r"><br>
    </label>
   
    <button type="submit" onclick="fun1()"> calculate </button>

    <p id="result">
   </p>
  </form>

  <script type="text/javascript">
 
  </script>

  </body>
  </html>

][1]


Solution

  • Your values are a,b,c, not p,n,r. So use a,b,c to calculate result. And use preventDefault() when the form is submitted so that the page does not refresh.

        function fun1(event)
        {
        event.preventDefault()
          var a = document.getElementById('p').value ;
          var b = document.getElementById('n').value ;
          var c = document.getElementById('r').value ;
          var result = document.getElementById('result');
    
          result.innerHTML = "The interest is" + (a*b*c/100) ;
        }
    <form name="form1" onSubmit = "fun1(event)">
        <label> Enter Principal amount :
            <input type="text" id="p"><br>
        </label>
    
        <label> Enter no. of years :
            <input type="text" id="n"><br>
        </label>
    
        <label> Enter rate  :
            <input type="text" id="r"><br>
        </label>
       
        <button> calculate </button>
    
        <p id="result">
       </p>
      </form>