javascript - onclick 事件未在 HTML 上运行选择下拉
问题描述
我目前有一个HTML选择下拉列表,其中有六个选项,我要实现的只是选择“其他”选项出现JavaScript警报时,但是由于某种原因,我无法使其工作。
我已经尝试将 onclick 移动到选择标签而不是选项标签,并将警报移动到参数之外,这使得它可以在单击下拉列表后立即出现,但这不是我想要实现的.
function otherPayment() {
var paymentType = document.getElementById("paymentType").value;
if (paymentType == "Other") {
alert("test");
}
}
<div class="form-group">
<label for="paymentType">Payment Type:</label>
<select class="form-control" id="paymentType" name="paymentType" required>
<option value="">-</option>
<option value="Payment (Initial)">Payment (Initial)</option>
<option value="Payment (Full)">Payment (Full)</option>
<option value="Payment (Balance)">Payment (Balance)</option>
<option value="Delivery Fee">Delivery</option>
<option onclick="otherPayment()" value="Other">Other</option>
</select>
</div>
解决方案
<option>
元素的行为不像普通的 HTML 元素,所以onclick
不做任何事情。
最简单的方法是使用onchange
select 的事件,然后检查新选择的元素,如下所示:
function handlePaymentChange(event) {
var paymentType = event.target.value;
if (paymentType == "Other") {
alert("test");
}
}
<div class="form-group">
<label for="paymentType">Payment Type:</label>
<select class="form-control" id="paymentType" name="paymentType" required onchange="handlePaymentChange(event)">
<option value="">-</option>
<option value="Payment (Initial)">Payment (Initial)</option>
<option value="Payment (Full)">Payment (Full)</option>
<option value="Payment (Balance)">Payment (Balance)</option>
<option value="Delivery Fee">Delivery</option>
<option value="Other">Other</option>
</select>
</div>
推荐阅读
- android - 如何取消在调试期间安装的应用程序
- python - Conda 仅在基础环境中安装软件包
- c - 为什么需要转换字符?
- direct2d - 如何访问 Direct2D 硬件 RenderTarget 的位图数据?
- python - python中.sort()方法的意外输出
- scala - 在对象构造之前更新构造函数参数
- javascript - 使用 Nightmare Cloud 功能进行 Web 抓取可以在本地工作,但在部署时不能
- javascript - 为什么无论我点击哪个段落,我都会得到相同的输出?
- python - Telepot 中的样式内联键盘
- python-3.x - Python 对象超出递归深度