[英]onclick Event Not Running on HTML Select Drop Down
我目前有一個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
不會執行任何操作。
最簡單的方法是使用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>
你必須使用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>
最簡單的方法是使用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
,因此它應該運行良好。
我建議綁定下拉列表的onchange事件而不是選項的click事件。
<select class="form-control" id="paymentType" onchange="otherPayment()" name="paymentType" required>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.