I have written some JavaScript code that is supposed to add another element with a value of 1 when I click a button. However, currently it is resetting the array so only one element gets added each time. How can I fix this issue?
var x = document.getElementsByTagName('button');//return button array
var age_array = [];
smoker_array = [];
relation_array = [];
age = 0;
//add button clicked
x[0].addEventListener("click", function(){
/*
var age = document.getElementsByName("age")[0].value;//pull age from box
var relation = document.getElementsByName("rel")[0].value;//pull relation
let smoker = document.querySelector('[name=smoker').checked;
//check relation
if(relation === "")
{
alert("please select a realation");
}
//check to see if age < 0
if(age < 0 || age === " ")
{
alert("age not applicable");
}
*/
age_array.push(1);
alert(age_array.length);
});
/*function submit(age, relation, smoker)
{
age_array.push(age);
alert(age_array[0]);
alert(age_array[1]);
/*
x[1].addEventListener("click", function(){
var age = JSON.stringify(entry_age);
alert(entry_age[1]);
document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);
});
}
*/
Below is the HTML code for reference:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="index.js"></script>
</body>
</html>