What are some best practices for using JavaScript to automatically populate form fields based on radio button selections in PHP?

When working with radio buttons in a form, you may want to automatically populate other form fields based on the selected radio button. This can be achieved using JavaScript to listen for changes in the radio button selection and then update the corresponding form fields accordingly. Below is an example PHP code snippet that demonstrates how to achieve this functionality.

<form>
  <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="text" name="selected_color" id="selected_color">
</form>

<script>
  const colorRadios = document.querySelectorAll('input[name="color"]');
  const selectedColorField = document.getElementById('selected_color');

  colorRadios.forEach(radio => {
    radio.addEventListener('change', function() {
      selectedColorField.value = this.value;
    });
  });
</script>