简体   繁体   中英

Function keeps returning undefined

I have been trying to get this function to run for about an hour now and it is driving me insane.

Here is my JS file

function hannaford(){
 var x = document.getElementByName("hList").value;
 x =parseInt(x);
 var i;
var hannafordResp = ["Responsibility 1", "Responsibility 2", "Three", "Four", "Five"];
for(i=0; i<x-1; i++){
    document.getElementById("hannafordResult").innerHTML = (hannafordResp[i]) + "<br />"
}

}

Here is the relevant HTML code.

    <div class="experience clearfix">
    <h3>Hannaford Supermarkets</h3>
    <p>
    Position
    <br />
    Location
    <br /> <br />
    2013-2015
    </p>
    <p>How many responsibilities?(max 5)</p>
    <input type="text" name="hList" >
    <input type="button" value="Go" onclick="hannaford()" >

    <p id="hannafordResult"> </p>


    </div>

The error message I get is ReferenceError: hannaford() is not defined.

I have checked syntax thoroughly, but nothing seems to work. Any posibilities?

Go ahead and run this code snippet. You needed to use getElementsByName (you were using Element ). This returns an array, so you need to get the 0th return's value.

Then your for-loop should be going to x, not x-1

 function hannaford(){ var x = document.getElementsByName("hList")[0].value; x =parseInt(x); var i; var hannafordResp = ["Responsibility 1", "Responsibility 2", "Three", "Four", "Five"]; for(i=0; i<x; i++){ document.getElementById("hannafordResult").innerHTML = (hannafordResp[i]) + "<br />" } } 
 <div class="experience clearfix"> <h3>Hannaford Supermarkets</h3> <p> Position <br /> Location <br /> <br /> 2013-2015 </p> <p>How many responsibilities?(max 5)</p> <input type="text" name="hList" > <input type="button" value="Go" onclick="hannaford()" > <p id="hannafordResult"> </p> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM