首页 > 解决方案 > 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>

标签: javascripthtml

解决方案


<option>元素的行为不像普通的 HTML 元素,所以onclick不做任何事情。

最简单的方法是使用onchangeselect 的事件,然后检查新选择的元素,如下所示:

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>


推荐阅读