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>
CodePudding user response:
<input type="radio" name="discounts" id="discount_A" onclick="insertDiscount(''.$total_discount);">
A few things need to change.
- Since you have the
insertDiscount()
with the()
it is called immediately and not onclick- You need to use
insertDiscount.bind(this, variable)
- You need to use
- Next, to output the value of
$total_discount
you need to<?= $total_discount; ?>
which will echo the value
So your final result will look something like this.
onclick="insertDiscount.bind(this, '<?= $total_discount; ?>'">
CodePudding user response:
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.