テキストフォーム増殖
友人の会社の研修で、javascriptを使ってフォームを増やしていく、という課題が出たそうだ。ということで、勝手にその課題をやってみた。
<html> <head> <title>test</title> <script type="text/Javascript"> <!-- function addQuestion(id) { var next_id = id + 1; if (document.getElementById(next_id)) { return; } var h2 = '<h2>質問' + next_id + '</h2>'; var q_id = 'q' + next_id; var textarea = '<textarea name="question"' + next_id + '" id="' + q_id + '"></textarea><br>'; var url_area = '<div id="url' + next_id + '"></div>'; var button = '<input type="button" value="質問追加" onClick="addQuestion(' + next_id + ')"> '; button += '<input type="button" value="質問' + next_id + 'に対するURL追加" onClick="addUrl(' + next_id + ')">'; var div = '<div id="' + next_id + '">'; div += textarea; div += url_area; div += button; div += '</div>'; document.getElementById('enq').innerHTML += h2 + div; } function addUrl(id) { var u_id = 'url' + id; var form = 'URL:<input type="text" id="' + u_id + '" name="' + u_id + '">'; document.getElementById(u_id).innerHTML = form; } //--> </script> </head> <body> <h1>フォーム増殖テスト</h1> <!-- テキストエリアが増えるところ --> <div id='enq'> <h2>質問1</h2> <div id="1"> <textarea name="question1" id="q1"></textarea><br> <div id="url1"></div> <input type="button" value="質問追加" onClick="addQuestion(1)"> <input type="button" value="質問1に対するURL追加" onClick="addUrl(1)"> </div> </div> </body> </html>
仕事ではperlしか書いていないので、javascriptに対する知識が足りない。
なんだか力技になってしまっている感がある。フォーム操作関係のJavaScriptのソースを読んでみたい。