How can PHP be used to dynamically generate radio buttons for selecting shipping providers and displaying their corresponding costs based on weight?
To dynamically generate radio buttons for selecting shipping providers and displaying their corresponding costs based on weight in PHP, you can create an array of shipping providers with their respective costs. Then, loop through this array to generate radio buttons for each provider. Use JavaScript to calculate the cost based on the selected provider and weight, and display it dynamically on the page.
<?php
// Array of shipping providers and their costs per unit weight
$shipping_providers = [
'Provider A' => 1.5,
'Provider B' => 2.0,
'Provider C' => 2.5
];
// Display radio buttons for each shipping provider
foreach ($shipping_providers as $provider => $cost) {
echo '<input type="radio" name="shipping_provider" value="' . $provider . '">' . $provider . '<br>';
}
// JavaScript to calculate and display cost based on selected provider and weight
echo '<script>
document.querySelector(\'input[name="shipping_provider"]\').addEventListener(\'change\', function() {
var weight = 10; // Example weight
var cost = weight * parseFloat(this.value);
document.getElementById(\'shipping_cost\').innerHTML = "Shipping Cost: $" + cost.toFixed(2);
});
</script>';
// Display element for showing the calculated shipping cost
echo '<div id="shipping_cost"></div>';
?>