我目前有一个HTML select下拉列表,其中包含六个选项,我想要实现的是选择了“ Other”选项时出现了JavaScript警报,但由于某种原因我无法使它起作用。
我尝试将onclick移到select标记而不是option标记,并将警报移到参数之外,这样一经单击下拉列表,警报便会出现,但这是可行的,但我不是试图实现。
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>
答案 0 :(得分:5)
<option>
元素的行为不像普通的HTML元素,因此onclick
不会做任何事情。
最简单的方法是使用select的onchange
事件,然后检查新选择的元素,如下所示:
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>
答案 1 :(得分:3)
您必须在onchange
标签上使用select
,而不要在option
标签上使用。
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 onchange="otherPayment()">
<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>
答案 2 :(得分:0)
最简单的方法是使用onselect
:
<div class="form-group">
<label for="paymentType">Payment Type:</label>
<select class="form-control" id="paymentType" name="paymentType" onselect="otherPayment()" 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 value="Other">Other</option>
</select>
</div>
因为已经有一个if/else
,它应该可以正常工作。
答案 3 :(得分:0)
我建议绑定下拉菜单的 onchange 事件,而不是绑定选项的 click 事件。
<select class="form-control" id="paymentType" onchange="otherPayment()" name="paymentType" required>