I am new to php and I am trying to display a value ($total_discount) to a textbox when radio button is clicked. But whenever my radio button is clicked, it only outputs a text 'undefined'. This is my code
<script type="text/javascript">
function insertDiscount(getDiscount) {
document.getElementById("discount").value = getDiscount;
}
</script>
<?php
$quantity = $_POST["quantity"];
$discount_a = 0.10;
$discounted_price;
$total_discount;
if(isset($item_price)){
$discounted_price = $item_price * $discount_a;
$total_discount = $discounted_price * $quantity;
}
?>
<input type="text" name="discount" id="discount" value="">
<input type="radio" name="discounts" id="discount_A" onclick="insertDiscount(''.$total_discount);">
<label for="discount_A">10% Discount</label>
$total_discount variable is undefined.$total_discount is not null.$total_discount is a not null then you can pass $total_discount in javascript function insertDiscount() function.$total_discount is null or undefined then you can assign $total_discount variable value and pass in javascript function insertDiscount() function.Example code
<?php if(isset($total_discount)): ?>
<input type="radio" name="discounts" id="discount_A" onclick="insertDiscount(<?=$total_discount?>);">
<?php else: ?>
<!-- First you can assign $total_discount variable value then pass it -->
<?php $total_discount = 10; ?>
<input type="radio" name="discounts" id="discount_A" onclick="insertDiscount(<?=$total_discount?>);">
<?php endif ?>
<input type="radio" name="discounts" id="discount_A" onclick="insertDiscount(''.$total_discount);">
$total_discount you need to <?= $total_discount; ?> which will echo the valueSo your final result will look something like this.
onclick="insertDiscount('<?= $total_discount; ?>')">
PHP is not rendering the value of the variable $total_discount.
Chanage
onclick="insertDiscount(''.$total_discount);"
to
onclick="insertDiscount(<?php echo($total_discount); ?>)"
to achieve the desired result.