How can one efficiently toggle visibility of input fields based on radio button selection in PHP?
To efficiently toggle visibility of input fields based on radio button selection in PHP, you can use JavaScript to handle the client-side behavior and PHP to dynamically generate the input fields based on the selected radio button. You can use JavaScript to listen for the change event on the radio buttons and show/hide the corresponding input fields accordingly.
<?php
// PHP code to dynamically generate input fields based on radio button selection
$selectedOption = isset($_POST['option']) ? $_POST['option'] : '';
echo '<form method="post">';
echo '<input type="radio" name="option" value="option1" onchange="this.form.submit()"';
if ($selectedOption === 'option1') {
echo ' checked';
}
echo '> Option 1';
echo '<input type="radio" name="option" value="option2" onchange="this.form.submit()"';
if ($selectedOption === 'option2') {
echo ' checked';
}
echo '> Option 2';
echo '</form>';
if ($selectedOption === 'option1') {
echo '<input type="text" name="field1" placeholder="Field 1">';
} elseif ($selectedOption === 'option2') {
echo '<input type="text" name="field2" placeholder="Field 2">';
}
?>
Keywords
Related Questions
- Are there any best practices for structuring PHP code to handle dynamic query building based on user input?
- What are potential pitfalls of including multiple PHP files in a single webpage?
- What are the potential pitfalls of inserting multiple records from a dynamically generated table into a database using PHP?