简体   繁体   中英

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?

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>
    ';
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM