onclick
テキストフィールドの入力値を取得するために、イベントハンドラーを使用できます。次の方法id
で安全に参照できるように、フィールドに一意の属性を指定してくださいdocument.getElementById()
。
要素を動的に追加する場合は、要素を配置するコンテナが必要です。たとえば、<div id="container">
。document.createElement()
を使用appendChild()
して新しい要素を作成し、を使用して各要素をコンテナに追加します。意味のあるname
属性を出力することに興味があるかもしれません(たとえば、フォームで送信する場合name="member"+i
は、動的に生成されたのそれぞれについて<input>
。
を使用して<br/>
要素を作成することもできますdocument.createElement('br')
。テキストを出力するだけの場合は、document.createTextNode()
代わりに使用できます。
また、コンテナにデータが入力されるたびにコンテナをクリアしたい場合はhasChildNodes()
、removeChild()
一緒に使用できます。
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Number of inputs to create
var number = document.getElementById("member").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
このJSFiddleの作業サンプルを参照してください。
Uncaught TypeError: Cannot call method 'appendChild' of undefined