我有一张表格。填写表单后,您可以从列表中添加或删除条目。一切正常。我想要工作的是,一旦所有条目都被添加到列表中并且人员点击提交,我希望序列化列表中的数据。
表单提交是我到目前为止所做的工作,我把它带到了最新的条目,但不是列表中的所有内容。
<html>
<head>
<meta charset="utf-8">
<title>Home 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 name="myForm" method="post" >
<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>
<label id="house">Home
<select id="homelist" size="9">
<option></option>
</select>
</label>
</div>
<div>
<button type="button" onclick="validateForm()">add</button>
<button type="button" onclick="removeList()">Remove</button>
<button type="submit" onclick="Submission()">submit</button>
</div>
</form>
<!-- <div id="results"> </div> -->
</div>
<pre class="debug" id="results"> </pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script >
function Submission() {
var x = $('#household :input').serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " ");
})
}
function validateForm() {
var x = document.forms["myForm"]["age"].value;
if (isNaN(x)|| x == ""|| x < 0) {
alert("Age must be filled out and must be greater than 0");
return false;
}
else
addList();
}
function addList() {
var x = document.getElementById("homelist");
var option = document.createElement("option");
option.text = ("Relationship: "+ document.forms["myForm"]["rel"].value + " Age: "+document.forms["myForm"]["age"].value+" Smoker: "+document.forms["myForm"]["smoker"].checked);
x.add(option)
}
</script>
</body>