getelementsbyname not returning any value

hamptonus picture hamptonus · Dec 17, 2012 · Viewed 18.3k times · Source

I've spent all day reading tutorials but can't seem to find an answer to this basic question.

All I want to do is access the value of an input field. I've made a basic stub to try and teach myself. The desired behavior is that when I click the "submit" button, I should get an alert with the value of the number field "points". However, when I put the following code in my website, then click the submit button, nothing happens.

<script type="text/javascript">
    function checknumber()
    {
        var testnumber=document.getelementsbyname("points").value;
        alert(testnumber);
    }
</script>
<input type="number" name="points" value="1">Points<br>
<input type="submit" onclick="checknumber();">

What am I doing wrong?

Incidentally, if I get rid of the line with "getelementsbyname" and change the script as follows:

function checknumber()
{
    var testnumber="hello world";
    alert(testnumber);
}

Then everything works fine, I get an alert popup with the text "hello world" exactly as expected.

Any help will be greatly appreciated.

Answer

hridya pv picture hridya pv · Dec 17, 2012

Its because getElementsByName returns an HTMLCollection. So you have to use:

function checknumber()
{
    var testnumber=document.getElementsByName("point")[0].value;
    alert(testnumber);
}

or

function checknumber()
{
    var testnumber=document.getElementsByName("point")[0].value;
    alert(testnumber);
}

Here's the demo (click Run with JS, input any number and click the button; the alert will pop up).