これを行うには 2 つの方法があります。PHP のみを使用する方法と、高度な JavaScript を使用する方法です。PHPのみのソリューションに取り組みます。JavaScript ソリューションは、サーバーへのラウンドトリップが繰り返されないため、はるかに応答性が高くなりますが、JavaScript が有効になっているユーザーに対してのみ機能しますが、PHP ソリューションはすべての人に機能します.
ソリューションの概要は次のとおりです。
- 初期値
$count
は 1 で、1 行生成されます。
count
ユーザーが [追加] をクリックすると、フォームは非表示の変数が含まれたまったく同じ PHP ファイルに戻されます。スクリプトは最初から再開し、 をインクリメントし$count
て、前回よりも 1 行多く表示します。
- ユーザーが [送信] をクリックすると、入力された名前が処理されます。
ここにいくつかのサンプルコードがあります。これを書いているマシンに PHP がインストールされていないことをお詫びします。そのため、これは完全にテストされていません。恐ろしい構文エラーが多すぎないことを願っています!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
ああ、JavaScript ソリューションが必要ですね。さて、あなたはすでに本当に素晴らしいjQueryの答えを持っています. では、途方もなく長いプレーンな JavaScript ソリューションはどうでしょうか?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>