0

我是 PHP 新手,正在制作一个网站以在给定的基础中添加任意数量的值。如何根据用户在前一个字段中的输入生成多个字段?

4

2 回答 2

3

没有任何验证的简单代码将是这样的:

<?php

if (isset($_POST['count_of_fields'])) {
    echo '<form method="POST" action="">';
    for ($i = 0; $i < (int) $_POST['count_of_fields']; ++$i) {
        echo '<input type="text" name="field[$i]" /><br>';
    }
    echo ' <input type="submit"></form>';
} else {
    echo '
        <form method="POST" action="">
        <input type="number" name="count_of_fields">
        <input type="submit">
        </form>
    ';
}
于 2021-10-28T12:43:10.077 回答
1

除了@lis-dev 在服务器端生成字段的答案之外,您每次都必须加载页面以呈现新字段,让我们使用 JavaScript 为您执行此操作,而无需刷新页面。是的,使用 mix 和 max 你也可以限制

function generate()
{
  var value = parseInt(document.getElementById("no").value);
  for(var i =1; i <= value ; i++)
  {
     var input = document.createElement("input");
     var br = document.createElement("br");
     input.type = "text";
     input.placeholder = "I am dynamic field " + i;
     document.getElementById('form').appendChild(input);
     document.getElementById('form').appendChild(br);
  }
}
<html>
<head>
    <title>dynamic fields test</title>
</head>
<body>
<form id="form">
<input id="no" type="text" min="5" max="10" placeholder="Enter no of Fields">
<input type="button" value="Generate" onclick="generate()">
<br />
</form>
</body>
</html>

于 2021-10-28T13:36:06.887 回答