Reputation: 634
Whenever my form is submitted nothing happens and when I check my array on the console it remains empty. In order to target values of input I need to put it in a function I also use return in function but nothing happens. Actually I want user data collected in object and push into array whenever I click on submit button...
var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Gender: inputsarray[6, 7].checked,
Purpose: inputsarray[8, 9, 10].checked
};
array.push(users);
}
<div>
<center>
<form method="post" onsubmit="subm();">
<label for="fname">First Name:</label> 
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label> 
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label> 
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>  
<input type="text" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>  
<input type="date" id="dob" />
<br/>
<label>Age:</label>     
<input type="text" id="age" />
<br/>
<span>Gender:</span>     
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Upvotes: 1
Views: 104
Reputation: 944568
When you push the submit button, you start the form submission process.
First the onsubmit function runs. This modifies your array.
Then the form submits and loads a new page.
This is (presumably) the same page that the user is already looking at. It's a fresh copy of it though, so it doesn't contain the array from the old version of it.
You can return false;
at the end of the onsubmit
function to prevent form submission.
Modern code would use addEventListener
(introduced about two decades ago) and call the preventDefault
method of the event object.
document.querySelector("form").addEventListener("submit", subm);
function subm(event) {
event.preventDefault();
// etc
}
Upvotes: 3