在HTML上进行默认检查的单选按钮值显示?
因此,我的JS函数可以检查是否选择了单选按钮,然后像正常情况一样在我的HTML上显示值。
我的问题是它仅在设置为0时才有效。我将如何更改此操作,以便如果我在我的HTML无线电输入中使用$ 5的检查
选项,它也会在我的浏览器中显示该值吗?
如果我将检查
选项更改为其他提示
值,它仍然显示为0作为起始值,因为我没有单击任何内容。
这是我的JS代码
window.tip = 0;
const tipTotal = document.getElementById("tip");
const orderTotal = document.getElementById("total");
document.addEventListener("click", ({
target
}) => {
if (target.className === "tips" && target.checked) {
window.tip = parseInt(target.value);
} else {
return;
tipTotal.textContent = `$${window.tip}`;
}
我显示选定的广播按钮,
<td id="tip">$0.00</td>
这是我的HTML广播按钮
<input type="radio" value="0" id="tip0" name="tip" class="tips" />
<label for="tip0">$0</label>
</div>
<div>
<input type="radio" value="300" id="tip1" name="tip" class="tips" />
<label for="tip1">$3</label>
</div>
<div>
<input type="radio" value="500" id="tip2" name="tip" class="tips" checked //here is the default checked option for $5 />
<label for="tip2">$5</label>
</div>
,因此,默认情况下,我的应用将显示提示:$ 5
选项已选中,但是,浏览器上的HTML for 提示
会说提示:$ 0.00
而不是提示:$ 5.00
,除非我单击它
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它仅在单击单击单击单击时,才设置
window.tip
,因为您添加了仅在单击时触发的事件侦听器。您可以添加一个on Load Event侦听器。我还在第一个事件听众中删除了不必要的其他陈述。
编辑
自动更新
tiptotal
文本:It sets
window.tip
only when a radio button is clicked because you added an event listener that fires only on click. You can add an on load event listener.I also removed an unnecessary else statement in the first event listener.
EDIT
Automatically update
tipTotal
text:首先,您还拥有一个名为“提示”的全局变量,还有一个带有
ID
的元素。具有id
s的元素也成为全局,因此您在命名方面有冲突。接下来,您需要在JS中以及提示量更改时最初更新该
TD
。First, you've got a Global variable called "tip" and an element with an
id
of "tip" as well. Elements withid
s also become Global and so you've got a conflict in naming.Next, you need to initially update that
td
in your JS and also when the tip amount changes.只需触发
tip2
单击“单击事件”事件:例如:
Simply trigger a
tip2
radio button click event:For example: