PHP中点击单选按钮向文本框赋值出现undefined如何解决
你代码的问题出在3处:
- 单选按钮的
onclick事件中没有正确输出PHP变量$total_discount的值,PHP代码必须用<?php ?>标签包裹才会被服务器解析执行,你当前的写法里$total_discount只是普通的HTML文本,不会被替换成PHP变量值 $total_discount仅在isset($item_price)判断成立时才会被赋值,你没有给$item_price做初始化也没有给$total_discount设置默认值,变量未定义时输出到前端就是空值或者异常- 你在
onclick里写的''.$total_discount拼接语法完全错误,既不是PHP拼接也不是JS拼接逻辑
修复后的完整代码
<script type="text/javascript"> function insertDiscount(getDiscount) { document.getElementById("discount").value = getDiscount; } </script> <?php // 这里补充你$item_price的实际取值逻辑,以下为示例固定值 $item_price = 100; // 给POST参数加判空,避免未定义警告 $quantity = isset($_POST["quantity"]) ? intval($_POST["quantity"]) : 1; $discount_a = 0.10; // 先给变量设置默认值 $discounted_price = 0; $total_discount = 0; if(isset($item_price)){ $discounted_price = $item_price * $discount_a; $total_discount = $discounted_price * $quantity; } ?> <input type="text" name="discount" id="discount" value=""> <!-- 正确用PHP输出$total_discount的值到onclick参数里 --> <input type="radio" name="discounts" id="discount_A" onclick="insertDiscount(<?php echo htmlspecialchars($total_discount); ?>)"> <label for="discount_A">10% Discount</label>
额外提示
如果你的商品价格、购买数量是用户在前端页面可修改的,建议把折扣计算逻辑放到JS里实现,不要依赖服务端PHP的固定值,不然用户修改参数后计算出来的折扣还是页面首次渲染的旧值。
内容的提问来源于stack exchange,提问作者WiloWisk
相关产品推荐
相关产品推荐

