I’m new to PHP and making a website to add an arbitrary number of values in a given base. How would I generate several fields based on a user’s input in a previous field?
CodePudding user response:
The simple code without any validation will be like this:
<?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>
';
}
CodePudding user response:
Beside the answer from @lis-dev which is generating fields in server side you will have to load the page each time to render the new fields, let's use JavaScript to do that for you without refreshing the page. and yes using mix and max you can put limit also
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>