0

i m trying to get a list of outputs which doesn't divide evenly by number which are smaller than the input value.For example if the input value is 10,the list should be 10,9,8,7,6,4,3,1. below is my code and doesn't give me any output nor any error message.I m new to javascript and i need to know what i m doing wrong.

<HTML XMLns="http://www.w3.org/1999/xHTML"> 
<head> 
<title>An example of using "for" and "while" in PHP</title>
<script type="text/javascript">
function displayResult()
{
if(text_form.numberfield.value){
var number=document.getElementsByName("numberfield").value;
var div=document.getElementsByName("numberfield").value;
        while (div>0)
        {
            if(number%div==0 && div!=number && div!=1)
            {
                div--;
                continue;
            }
            if (div == 0)
            {
                break;
            }

        document.write(div--); 
        document.write(",");
        }


}
else
{
document.write("Enter a number");
}
}
</script>

</head> 
<body>
<H1>An example of using "for" and "while" in PHP</H1>

<form name="text_form">
    Please input a number:  <input type="text" name="numberfield"> </label> 

    <input type="submit" value="Submit" onclick="displayResult()" />
</form>

<p> Result is shown as below.</p>
</body>
</HTML>
koshi18
  • 53
  • 9
  • possible duplicate of [getElementsByName() not working?](http://stackoverflow.com/questions/6967297/getelementsbyname-not-working) – JJJ Sep 29 '13 at 06:57

2 Answers2

1

getElementsByName returns an array, not an element.

Try:

var number=document.getElementsByName("numberfield")[0].value;
var div=document.getElementsByName("numberfield")[0].value;

Notice the [0]. You also have to modify a bit to make it work.

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • `getElementsByName()` actually returns an HTMLCollection, which likes to pretend that it's an array but actually isn't. – Jackson Sep 29 '13 at 07:05
  • 1
    However (similar to `arguments`) you can access the object's members via numeric keys (as you have done, which is correct). – Jackson Sep 29 '13 at 07:06
0

the getElementsByName returns a list of elements having the specified name not a single element. You can access each element using loop:

var elems=document.getElementsByName("name")
for(var i=0;i<elems.length;i++){
var elem=elems[i]
//access each element using iterator
}

Also the getElementsByTagName returns a list of elements having the specified tag name.

Nishad K Ahamed
  • 1,374
  • 15
  • 25