2016-12-31 64 views
0

我打了一下墙。用我当前的JS如何在用户点击“添加”时在class =“household”中输出当前表单字段的结果?如何使用Javascript输出HTML表单数据?

*我仍然想保留删除功能。

我不能编辑HTML只JS。任何帮助欣然赞赏。谢谢!

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

将添加按钮更改为'type =“按钮”'。默认是'type =“submit”',所以它提交表单。 – Barmar

+0

@Barmar *“我不能编辑HTML只有JS”*我意识到用户可以改变这个使用JS,而不是通过简单地改变HTML –

回答

0

add按钮提交表单。您可以通过在处理函数中调用event.preventDefault()来阻止该问题。

document.querySelector(".add").onclick = function(event) { 
    event.preventDefault(); 
    createinput() 
}; 
+0

它的工作原理!战斗已经结束了,我需要实际显示值而不是输入字段。什么是最好的方法来做到这一点? – spidey677

+0

显示用户添加的内容的值。 – spidey677

+0

'document.getElementById(someID).value'将获得输入字段的值。 – Barmar

相关问题