0

I want to display divisors of a number in a text box using loop. But their is some error in my program.I need help to correct it.

`<html>
<head>
  <script>
  function CheckDivisors()
  {
     number=parseInt(document.divfrm.num.value);
     d=1,sp="\t";
     do
     { 
        if(number%d==0)
        {       
        document.divfrm.div.value=d;
        document.divfrm.div.value=sp;
        }       
      d++;

     }
     while(d<=number/2);
  }
  </script>
  </head>
 <body>
 <form name="divfrm">
 Enter a number: <input type="text" name="num">
 <br>
 Divisors: <input type="text" name="div">
 <br>
 <input type="button" value="Display Divisors" onClick="CheckDivisors()">
</form>
</body>
</html>
`
4
Contributors
5
Replies
6
Views
4 Years
Discussion Span
Last Post by Zaina jee
2

it is a good idea to use var when declaring variables. E.g var number. The reason being is that your variables will be easy to trace and and it is a good practice.

I guess you're trying to add the value to the textbox you've got there, right?

Try this

 document.divfrm.div.innerHTML=d;
 document.divfrm.div.innerHTML=sp;
0

I have tried your suggestions but still it is not working.

0

you are overwriting pervious value, keep on appending as shown below, with + before =

document.divfrm.div.value+=d;
document.divfrm.div.value+=sp;
2

Try this:

<html>
<head>
  <script>
  function CheckDivisors()
  {
     var 
        number=parseInt(document.divfrm.num.value),
        d=1,
        divisors = [];
     do
     { 
        if(number%d==0)
        {       
            divisors.push(d);
        }       
      d++;
     }
     while(d<=number/2);

     document.getElementById("divDivisors").value = divisors.join(", ");
  }
  </script>
  </head>
 <body>
 <form name="divfrm">
 Enter a number: <input type="text" name="num">
 <br>
 Divisors: <input type="text" name="div" id="divDivisors">
 <br>
 <input type="button" value="Display Divisors" onClick="CheckDivisors()">
</form>
</body>
</html>
`

It's not wise to make DOM changes inside a loop. DOM manipulation is heavy, so it's better to put gather all that you want to show and then show it all at once.

0

Thanks AleMonteiro. Now my program is working.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.