What are the correct HTML attributes to use for pre-selecting radio buttons in PHP forms for proper functionality?
When pre-selecting radio buttons in PHP forms, you can use the "checked" attribute in the input tag to specify which radio button should be selected by default. To do this, you need to dynamically generate the HTML code for the radio buttons in PHP and add the "checked" attribute to the input tag that corresponds to the pre-selected option.
<form action="submit.php" method="post">
<input type="radio" name="color" value="red" <?php if(isset($_POST['color']) && $_POST['color'] == 'red') echo 'checked'; ?>> Red
<input type="radio" name="color" value="blue" <?php if(isset($_POST['color']) && $_POST['color'] == 'blue') echo 'checked'; ?>> Blue
<input type="radio" name="color" value="green" <?php if(isset($_POST['color']) && $_POST['color'] == 'green') echo 'checked'; ?>> Green
<input type="submit" value="Submit">
</form>
Related Questions
- In what scenarios is it recommended to handle form data processing in PHP rather than using JavaScript?
- How can the use of var_dump() function help in debugging and understanding the structure of SESSION variables in PHP, as demonstrated in the forum thread conversation?
- What best practices should be followed when assigning and using random values to variables in PHP to ensure consistency in calculations?