How can PHP be used to dynamically generate a variable number of text fields in a form based on user input, such as the number of persons to be added?
To dynamically generate a variable number of text fields in a form based on user input, such as the number of persons to be added, you can use PHP in conjunction with HTML and JavaScript. One approach is to use a loop in PHP to generate the desired number of input fields, and then use JavaScript to dynamically display or hide these fields based on user input.
<?php
if(isset($_POST['num_persons'])){
$num_persons = $_POST['num_persons'];
for($i = 1; $i <= $num_persons; $i++){
echo '<input type="text" name="person_'.$i.'" placeholder="Person '.$i.' Name"><br>';
}
}
?>
<form method="post">
<label for="num_persons">Number of Persons:</label>
<input type="number" name="num_persons">
<input type="submit" value="Generate Fields">
</form>
Keywords
Related Questions
- What are the best practices for manipulating and transforming text content in PHP using regular expressions and other methods?
- What potential pitfalls should be considered when extracting file extensions from uploaded images in PHP?
- Are there any specific PHP functions or methods recommended for reading file contents?