简体   繁体   中英

Uncaught TypeError: Cannot set property 'innerHTML' of null using a for loop

Basically what I have for this code is I want to take the number of pets a user inputs, take down the names of the pets, and put them in a variable that I can print out later in the program.

{
return document.getElementById(id);
}
var processInfo = function ()
{
    //Setting varibles from HTML
    first = $('firstname');
    last = $('lastname');
    petnum = $('numpets');
    //For loop for pet names
    var Petlist = '';
    for (cntr = 1; cntr <= petnum.value; cntr++)
    {
        petID = 'pet' + cntr;
        PetName = $(petID).value;
        Petlist += PetName;
    }

    //Checking for blank strings to be filled
    /*var errorFoundFlag = 'N';

    if (something is found to have an error)
    {
        msg += "error found with something";
        errorFoundFlag = 'Y';
    }

    if (somethingElse is found to have an error)
    {
        msg += "error found with somethingElse ";
        errorFoundFlag = 'Y';
    }

    if (errorFoundFlag == 'N')
    {
       Do the processing called for in the "Success" section above
    }
    */



    $("msg").innerHTML = Petlist;

}

window.onload = function ()
{
$("mybutton").onclick = processInfo;
}
<p>How Many Pets do you have?  (0-3): <input type="text" id="numpets" size="1" maxlength="1">
<span id="numpets_error"></span>
</p>

<p>List your Pet's names:
    <input type="text" id="pet1">
    <input type="text" id="pet2">
    <input type="text" id="pet3">
</p>

<p><input id="mybutton" type="button" value="Submit Information"></p>

<p id="message"></p>

I want the for loop to take ids="pet1" "pet2" and "pet3" and put them together as a string into a variable called Petlist . I want to set inner.HTML to petlist , but I am getting the following error:

Uncaught TypeError: Cannot set property 'innerHTML' of null on line 43

where I call $("msg").innerHTML = Petlist

What am I doing wrong?

You are combining DOM with jQuery . That won't work.
Use the html method which is the jQuery equivalent of innerHTML .

$("msg").html(Petlist);

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