Skip to content
PHP Logo

How can a PHP developer display a certain number of text fields based on a user's selection from a select box?

To display a certain number of text fields based on a user's selection from a select box, you can use JavaScript to dynamically show or hide the desired number of text fields based on the selected option. You can use an onchange event listener on the select box to trigger the display of the text fields. Additionally, you can use PHP to process the form data once submitted.

php
<form method="post" action="process_form.php">
    <select name="num_fields" id="num_fields" onchange="showFields()">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    
    <div id="text_fields">
        <!-- Text fields will be dynamically added here based on user selection -->
    </div>
    
    <input type="submit" value="Submit">
</form>

<script>
function showFields() {
    var numFields = document.getElementById("num_fields").value;
    var textFields = document.getElementById("text_fields");
    
    textFields.innerHTML = "";
    
    for (var i = 0; i < numFields; i++) {
        textFields.innerHTML += '<input type="text" name="field' + (i+1) + '" placeholder="Field ' + (i+1) + '"><br>';
    }
}
</script>