[英]selecting radio buttons in a function
所以在這里,我有一個帶有單選按鈕和提交輸入的html表單。 我遇到的問題是選擇這些無線電輸入並在事件功能中提醒選中的那個。
<div id="shippingMethod">
<label>Shipping Method:</label><br>
<input type="radio" value="free Mail" name="r_method" id="freeMail" checked> <label for="freeMail">Free Mail (1 Month)</label><br>
<input type="radio" value="UPS" name="r_method" id="ups">
<label for="ups">UPS (1 week)</label><br>
<input type="radio" value="DHL" name="r_method" id="dhl">
<label for="dhl">DHL (2-4 days)</label>
<input type="submit" value="enter">
</div>
<script type="text/javascript">
document.getElementById('shopping').addEventListener('submit', actions);
function actions(event){
event.preventDefault();
var method = document.getElementById('shopping').r_method;
for (var i = 0; i < method.length; i++){
if(method[i].checked == "true"){
alert(method[i].value);
}
}
}
</script>
每次我進入控制台並鍵入“ method”時,都會說“ Uncaught ReferenceError:方法未定義”,但是我在動作函數中定義了方法。 而且,每當我按下“提交”輸入時,也不會發生任何事情。 但是,當我在控制台日志中創建此變量“方法”時。 有用。 我該如何解決這個問題?
嘗試這個
document.getElementById('shippingMethod').addEventListener('submit', actions); function actions(event){ event.preventDefault(); alert(document.querySelector('input[name="r_method"]:checked').value) }
<form id="shippingMethod"> <label>Shipping Method:</label><br> <input type="radio" value="free Mail" name="r_method" id="freeMail" checked> <label for="freeMail">Free Mail (1 Month)</label><br> <input type="radio" value="UPS" name="r_method" id="ups"> <label for="ups">UPS (1 week)</label><br> <input type="radio" value="DHL" name="r_method" id="dhl"> <label for="dhl">DHL (2-4 days)</label> <input type="submit" value="enter"> </form>
編輯
錯誤:
form
標簽。 事件submit
將永遠不會觸發,也永遠不會調用您的actions
功能 document.getElementById('shippingMethod').querySelectorAll('input[name="r_method"]');
而不是document.getElementById('shopping').r_method;
。 這樣,您將能夠遍歷包含所有元素的var method
。 使用for循環的工作示例是
document.getElementById('shippingMethod').addEventListener('submit', actions); function actions(event){ event.preventDefault(); var method = document.getElementById('shippingMethod').querySelectorAll('input[name="r_method"]'); for (var i = 0; i < method.length; i++){ if(method[i].checked == true){ alert(method[i].value) } } }
<form id="shippingMethod"> <label>Shipping Method:</label><br> <input type="radio" value="free Mail" name="r_method" id="freeMail" checked> <label for="freeMail">Free Mail (1 Month)</label><br> <input type="radio" value="UPS" name="r_method" id="ups"> <label for="ups">UPS (1 week)</label><br> <input type="radio" value="DHL" name="r_method" id="dhl"> <label for="dhl">DHL (2-4 days)</label> <input type="submit" value="enter"> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.