非常直截了當。HTML/Javascript表單如何將表單數據序列化爲JSON並顯示在類中?
當用戶點擊「提交」時,我需要表單序列化和JSON數據顯示在類「debug」中。
我如何用我目前的Javascript來做到這一點?
不能使用jQuery。無法編輯HTML。只有純粹的Javascript。
謝謝!
HTML
<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>
JS
function validate(form) {
fail = validateAge(form.age.value)
fail += validateRel(form.rel.value)
if (fail == "") return true
else {
alert(fail);
return false
}
}
function validateAge(field) {
if (isNaN(field)) return "No age was entered. \n"
else if (field < 1 || field > 200)
return "Age must be greater than 0. \n"
return ""
}
function validateRel(field) {
if (field == "") return "Please select a relationship \n"
return ""
}
document.querySelector("form").onsubmit = function() {
return validate(this)
}
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
}
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
var x = document.getElementsByName("age")[0].value;
var y = document.getElementsByName("rel")[0].value;
var z = document.getElementsByName("smoker")[0].checked;
if (!z) {
z = "Non smoker \n";
} else {
z = "Smoker \n";
}
p1.innerHTML = x;
p2.innerHTML = y;
p3.innerHTML = z;
li.appendChild(p1);
li.appendChild(p2);
li.appendChild(p3);
field_area.appendChild(li);
//removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
// serialize form
var data = {};
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => {
data[input.name] = input.value;
});
http://stackoverflow.com/questions/22195065/how-to-send-a-json-object-using-html-form-data – 0xcaff