What are some common pitfalls when using JavaScript to handle radio button selection in PHP forms?

One common pitfall when using JavaScript to handle radio button selection in PHP forms is not properly synchronizing the selected value with the PHP backend. To solve this, you can use JavaScript to update a hidden input field with the selected radio button value before submitting the form.

<form method="post" action="process_form.php">
    <input type="radio" name="color" value="red"> Red
    <input type="radio" name="color" value="blue"> Blue
    <input type="radio" name="color" value="green"> Green
    <input type="hidden" name="selected_color" id="selected_color">
    <button type="submit">Submit</button>
</form>

<script>
    document.querySelectorAll('input[type="radio"]').forEach(radio => {
        radio.addEventListener('change', function() {
            document.getElementById('selected_color').value = this.value;
        });
    });
</script>