[英]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.