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の作業サンプルを参照してください。