我撞到了一堵墙。使用我当前的JS,当用户点击“添加”时,如何在class =“household”中输出当前表单字段的结果?
*我仍然希望保留删除功能。
我不能只编辑HTML。任何帮助都很高兴得到赞赏。谢谢!
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>
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 > 1000)
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() {
createinput()
};
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the 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++
}
答案 0 :(得分:0)
add
按钮正在提交表单。您可以通过在处理函数中调用event.preventDefault()
来阻止这种情况。
document.querySelector(".add").onclick = function(event) {
event.preventDefault();
createinput()
};