寻找一种动态添加包含多个表单项的div的方法

时间:2016-02-19 23:31:11

标签: javascript html css

我的代码列在此https://jsfiddle.net/tek8b41g/1/

我想这样做,以便我可以添加另一个表格,如果我需要另一个"旅行"是否有捷径可寻?我正在考虑做隐藏的div,但想知道是否还有另一种方式。

提前致谢。

HTML:

<body bg=grey>
  <div id="wrap">
    <tr>
      <form method="POST"><br />
        <div id="center">
          <center>Driver Line Input page </center>
        </div>
        <br />
        <div class="centerDynamic">
          <label>
            <input type="radio" name="countyLabel" value="radio" id="countyLabel_0" />Eagle County</label>

          <label>
            <input type="radio" name="countyLabel" value="radio" id="countyLabel_1" />Summit County</label>
            <br />Driver Name: <input name="dNameT1" type="text" value="" size="25" /><br />Trip Time: <input name="tripTimeT1" type="text" value="" size="5" /><br />First Pickup: <input name="firstPickupT1" type="" value="" size="5" /><br />Town: <input name="townT1" type="text" value="" size="25" id="townT1" /><br />
           <label>Transfer during this trip:<input type="radio" name="transferYesT1" value="radio" id="transferGroup_1T1" />Yes</label>
           <label>
             <input name="transferNoT1" type="radio" id="transferGroup_1a" value="radio" checked="checked" />No</label>
              <br />
              <label for="transferDrivera">Transfer Driver</label> <input type="checkbox" name="transferDriverT1" id="transferDrivera" />
              <br />Need Carseat/Booster?<label>
              <input type="radio" name="carseatYesT1" value="radio" id="RadioGroup1_0" />Carseat</label>
              <label><input type="radio" name="boosterYesT1" value="radio" id="RadioGroup1_1" />Booster</label>
              <label><input type="radio" name="noneT1" value="radio" id="RadioGroup1_2" />None</label>
                 <br /><br />
        </div>
       <input type="button" value="Add Another Trip" onClick="addInput('centerDynamic');" />
      </form>
     </tr>
   </div>
 </body>

CSS:

 @charset "utf-8";
 /* CSS Document */

 #wrap { 
 width: 900px; 
 margin: 0 auto; 
 }
 #centerDynamic{
 width: 500px;
 margin: 0 auto;
 }

使用Javascript:

  var counter = 1;
  var limit = 34;
  function addInput(centerDynamic){
  if (counter == limit) {
     alert("You have reached the limit of adding " + counter + " inputs");
}
   else{
    var newdiv = document.createElement('div');
    newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>"; 
  document.getElementById(centerDynamic).appendChild(newdiv);
     counter++;
  }
  }

2 个答案:

答案 0 :(得分:1)

centerDynamicclassName,而不是id。此外,tr处有一个table元素,但没有html个父元素。尝试用document.querySelector("." + centerDynamic)代替document.getElementById(centerDynamic),删除tr元素

@charset "utf-8";

/* CSS Document */

#wrap {
  width: 900px;
  margin: 0 auto;
}
.centerDynamic {
  width: 500px;
  margin: 0 auto;
}
<body bg=grey>
  <div id="wrap">
    <form method="POST">
      <br />
      <div id="center">
        <center>Driver Line Input page</center>
      </div>
      <br />
      <div class="centerDynamic">
        <label>
          <input type="radio" name="countyLabel" value="radio" id="countyLabel_0" />Eagle County</label>

        <label>
          <input type="radio" name="countyLabel" value="radio" id="countyLabel_1" />Summit County</label>
        <br />Driver Name:
        <input name="dNameT1" type="text" value="" size="25" />
        <br>Trip Time:
        <input name="tripTimeT1" type="text" value="" size="5" />
        <br>First Pickup:
        <input name="firstPickupT1" type="" value="" size="5" />
        <br>Town:
        <input name="townT1" type="text" value="" size="25" id="townT1" />
        <br>
        <label>
          Transfer during this trip:
          <input type="radio" name="transferYesT1" value="radio" id="transferGroup_1T1" />Yes
        </label>
        <label>
          <input name="transferNoT1" type="radio" id="transferGroup_1a" value="radio" checked="checked" />No
        </label>
        <br />
        <label for="transferDrivera">Transfer Driver</label>
        <input type="checkbox" name="transferDriverT1" id="transferDrivera" />
        <br>Need Carseat/Booster?
        <label>
          <input type="radio" name="carseatYesT1" value="radio" id="RadioGroup1_0" />Carseat
        </label>
        <label>
          <input type="radio" name="boosterYesT1" value="radio" id="RadioGroup1_1" />Booster
        </label>
        <label>
          <input type="radio" name="noneT1" value="radio" id="RadioGroup1_2" />None
        </label>
        <br />
        <br />
      </div>
      <input type="button" value="Add Another Trip" onclick="addInput('centerDynamic');" />
    </form>
  </div>
  <script>
    var counter = 1;
    var limit = 34;

    function addInput(centerDynamic) {
      event.preventDefault();
      if (counter == limit) {
        alert("You have reached the limit of adding " + counter + " inputs");
      } else {
        var newdiv = document.createElement('div');
        newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
        document.querySelector("." + centerDynamic).appendChild(newdiv);
        counter++;
      }
    }
  </script>
</body>

答案 1 :(得分:1)

复制表格

目标:点击按钮复制表单。

解决方案:利用cloneNode()appendChild()方法

问题: OP的功能一般不足以处理目标。我们将继续探索解决方案,并尝试突出显示存在差异的某些区域,而不是列出错误列表。

HTML

  • #id :OP的代码没有重复的ID,但我提到这是因为这是一个常见的错误。在复制HTML时,务必记住should never be any duplicated ids

  • name :此属性广泛用于表单元素,与<input type="radio">一起使用时非常重要。对于每个 组的单选按钮 ,我们应始终为每个单选按钮分配 一个name 。这可确保只从组中选择一个单选按钮。

  • 提示:将idname分配给<form>和表单元素时,只需将它们设置为相同的值(使用单选按钮除外)。有关简短无偏见的解释,请参阅此post。有varying opinions on this topic,我的看法是,如果您在每个表单元素上使用相同的nameid,那么您可以使用所有选项,并且您不必担心是否使用了纠正一个或不。请注意,如果可能的话,请尽量保持idname简单但功能正常,特别是如果您打算复制并编号。

CSS

假设这只是一个草稿,而不是一个完成的项目,我们将不会涉及造型的细枝末节。注意,我已经明显改变了CSS,所以请随意提问或批评。

JS

我无法将OP的代码视为复制表单,它更像是一个扩展名:

<强>结果:

 // up to 34 extra identical inputs that don't match up to the original form.

 <br><input type='text' name='myInputs[]'>   

不太有用。以下是我在重复表格主题上看到的细节:

  • 使用JS复制表单的常用方法是使用方法cloneNode()appendChild()

  • 默认情况下,cloneNode()实际上是cloneNode(false),参数是一个布尔值,用于确定克隆的深度。如果设置为false或根本不设置,则cloneNode()将生成副本 - 所有属性,值和无子项。设置为true,将生成副本 - 所有后代,属性和值 - 所有内容(有一个例外 - 事件侦听器/绑定不会复制)。

  • 由于复制了所有属性,这也意味着id。我们必须通过收集克隆中的每个元素并为每个元素分配一个唯一的id来为此做出规定。该演示通过使用以下方式提供:

演示

JS中有一步一步的评论。我遗漏了一些细节,因为我不想让你入睡。请注意,这不是实现目标的唯一方法,这是众多目标之一。

Plunker

<强>段

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>35517008</title>
<style>
* { vertical-align: baseline; }
h2 { text-align: center; }
.center { margin: 0 auto; }
fieldset { margin: 0 auto; width: 50%; }
fieldset div { float: left; clear: left; }
#btn1 { position: relative; left: 65%; }
input[type="submit"] { float: right; }
input { margin: 0 5px 5px 0; }
label { padding: 0 0 5px 5px; }
input + input { margin-left: 10px; }

</style>
</head>

<body>

  <h2>Driver Line Input Page</h2>
<input id="btn1" class="center" type="button" value="Add Additional Trip" />

    <form id="line1" name="line1" method="post" class="center">
    <fieldset>
    <legend>Line 1</legend>
    <div>
      <label>
        <input type="radio" name="county" value="radio" id="eagle" />
        Eagle County
        <input type="radio" name="county" value="radio" id="summit" />
        Summit County
        </label>
     </div>
     <div>
      <label for="driver">Driver Name:
      <input name="driver" id="driver" type="text" size="25" />
      </label>
      </div>
      <div>
      <label for="time">Trip Time:
      <input name="time" id="time" type="text" size="5" />
      </label>
      <label for="pickup">First Pickup:
      <input name="pickup" id="pickup" type="text" size="5" />
      </label>
      
      <label for="city">City:
      <input name="ciy"  id="city" type="text" size="25" />
      </label>
      </div>
      <div>
      <label>Transfer Enroute:
        <input type="radio" name="trans" id="yes" />
        Yes
     
        <input type="radio" name="trans" id="no" checked />
        No
     </label>
     
      <label for="tDriver">Transfer Driver:
      <input name="tDriver" id="tDriver" />
      </label>
    </div>
    <div>
      <label>Carseat/Booster Request:
   
        <input type="radio" name="child" id="seat" />
        Carseat
     
        <input type="radio" name="child" id="booster" />
        Booster
      
        <input type="radio" name="child" id="none" checked />
        None
        </label>
        </div>
        <input type="submit" id="submit" name="submit"/>

</fieldset>
      <br />
      <br />
      
    </form>


<script>

/* When the "Add Additional Trip" button is clicked ... */
var btn1 = document.getElementById('btn1');
btn1.addEventListener('click', function(e) {
	
	// Collect all forms into a NodeList
  var forms = document.querySelectorAll('form');
	
	// Total number of forms and the new serial number
  var qty = forms.length;
	var step = (qty + 1).toString();
	
	// The original form
  var template = forms[0];
	
	// Make a clone of the original form
  var dupe = template.cloneNode(true);
	
	// Reference the clone's displayed title
	var line = dupe.querySelector('legend');
	
	// Set clone's title to Line {{number}}
	line.innerHTML = "Line "+ step;
	
	// Set clone's id and name to form{{number}}
  dupe.setAttribute('id', 'line'+ step);
	dupe.setAttribute('name', 'line'+ step);
	
	// Collect all of clone's inputs into a NodeList
	var inputs = dupe.querySelectorAll('input');
	
	// Convert the NodeList into an Array
	var inpArray = Array.prototype.slice.call(inputs);
	
	// Iterate through the Array and assign a unique id and name to each one
	for(var i = 0; i < inpArray.length; i++) {
		var inpID = inpArray[i].getAttribute('id');
		var inpName = inpArray[i].getAttribute('name');
		inpArray[i].setAttribute('id', inpID + step);
		inpArray[i].setAttribute('name', inpName + step);
	}
	
	// Place clone after the last form
  document.body.appendChild(dupe);
}, false);
</script>
</body>
</html>