Uncaught TypeError when calling function from button

Roger Wang :

I'm making a form to record data from a group of people, and when pressing the button to add another person, the console spits out a TypeError, saying addPerson() is not a function.

HTML (body):

<form method="POST">
    <h3> People </h3>
    <div class="person">
        <p>
            <label>Name</label>
            <input type="text" name="name" />
            <br/>
        </p>
        <p>
            <label>Gender</label>
            <input type="radio" name="gender" value="male" />Male
            <input type="radio" name="gender" value="female" />Female
            <br />
        </p>
        <p>
            <label>Date of Birth</label>
            <input type="date" name="dob" />
            <br/>
        </p>
    </div>
    <br/>
    <input type="button" value="Add another person" onclick="addPerson()" id="addPerson" />
</form>
<script src="client.js"></script>

Javascript:

function addPerson(){
    let personForm = document.getElementsByClassName("person")[0];
    let personFormCopy = personForm.cloneNode(true);
    let buttonNode = document.getElementById("addPerson");
    document.body.insertBefore(personFormCopy, buttonNode);

    let br150 = document.createElement("br");
    document.body.insertBefore(br150, buttonNode);

    br150.style.lineHeight="150px";
}

Error:

Uncaught TypeError: addPerson is not a function at HTMLInputElement.onclick
blex :

The name of your function and the button ID are the same. Ever since IE introduced this behavior, some browsers add DOM element IDs to the window scope, which is causing conflicts in your case.

This problem can be solved by changing the ID of the button to addPersonBtn, for example.

However, I would suggest not mixing HTML and JS. You could instead remove the onclick attribute in your HTML, and write your JS like so:

document.getElementById('addPersonBtn').addEventListener('click', addPerson);

function addPerson(){
    console.log('It worked.');
}
<button id="addPersonBtn">Click me</button>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=302016&siteId=1