Member Avatar for Zaina jee

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>
`

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;
Member Avatar for Zaina jee

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

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

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

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.

Member Avatar for Zaina jee

Thanks AleMonteiro. Now my program is working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.