metal.slime.angel
metal.slime.angel

Reputation: 43

HTML/Javascript form resets automatically

I'm writing javascript that takes in a form and prints it as a "verification" to 'id="printpeople"'. And it works, but after about three seconds, the form refreshes itself, and so does the p tag. The page doesn't seem to refresh itself unless I hit the 'submit' button. Why is this happening?

HTML:

<form name="form" id="form" class="form" onsubmit="createperson()" method="post">
    <label for="name">Full Name:</label>
    <input type="text" name="name" id="name" /><br>
         ...
    <input type="submit" value="Submit" class="submit" />
</form><br>
<p>People:</p>
<p id="printpeople"></p>

Javascript:

function person(form){
    var name = document.forms["form"]["name"].value;//retrieves name field
      ...
    var person = [name,email,gender,address];//creates new person array
    return person;
}

function createperson(form){
    var personinstance = person(form);
    var personstring = "Name "+personinstance[0]+
            "\n"+"Email "+personinstance[1]+
            ...
    stringholder(personinstance, "write");
}

window.peoplecriteria = ["Name: ","Email: ","Gender: ","Address: "];
window.peoplearray = []; //stores all the people in here
window.peoplestring = "";//string that's used for pretty printing.

function stringholder(parameter, readwrite){
    window.peoplearray.push(parameter);
    window.peoplestring += window.peoplecriteria[0]+window.peoplearray[0];
    document.getElementById("printpeople").innerHTML = peoplestring;
}

Upvotes: 1

Views: 1322

Answers (2)

grepsedawk
grepsedawk

Reputation: 3411

By using:

<form name="form" id="form" class="form" onsubmit="createperson();return false" method="post">

You should prevent the form from submitting itself.

This works by making the submit function return false. By default the onsubmit function returns true. By returning false, you state that you do not want the submission to carry through.

Upvotes: 3

abagshaw
abagshaw

Reputation: 6582

You might be able to stop the form from submitting with the following as your first line in createperson(form):

form.preventDefault();

Upvotes: 0

Related Questions