Skip to content
Advertisement

How to scale the number of form fields based on user input?

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?

Advertisement

Answer

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>
    ';
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement