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

Time:03-10

[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]

CodePudding user response:

Firstly, your formula is a * b * c, small typo.

You have a button of type submit inside a form. To fix this, pass the event object to the function and disable the default behaviour.

<button onclick="fun1(event)">

fun1(e) {
  e.preventDefault()

  ...
}

CodePudding user response:

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>

  • Related