html 表单动态添加输入项,并以数组的形式发送

name写成 "arr[]"的形式就可以了

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>作业管理</title>

</head>
<body>
<form enctype="multipart/form-data" method="POST" >
  <div id="postform">
    本次作业标题
      <input type="text" name="title" />
      <br>
    <div class="postoption"> 
      添加项目
      <input type="text" name="option[]" />
      音频文件
      <input type="file" name="radio[]" />
      答案
      <input type="text" name="answer[]" />
    </div>
  </div>

  <input type="submit" value="提交" />
</form>
  <button id="add">添加输入项</button>
<script type="text/javascript">

window.onload = function(){
  var add = document.getElementById("add");
  add.onclick = function(){
    addOption();
  }
}
function addOption(){
  var postForm = document.getElementById("postform");
  var postoptions = document.getElementsByClassName("postoption");
  var op = postoptions[0];
  var optionClone = op.cloneNode(true);
  postForm.appendChild(optionClone);
};

</script>
</body>
</html>

button不能放在form里面,不然就会提交,不知道为什么

SO 里问了一下,回答是

The <button> element is a submit button by default. You can change this with the type="button"attribute, which makes it do nothing by default, or calling preventDefault on the event. But I'd go with the attribute since then your intention is semantically clear without actually running the script.

posted @ 2014-02-27 09:29  ggaaooppeenngg  阅读(1374)  评论(0编辑  收藏  举报