gpt4 book ai didi

javascript - 验证 JavaScript 中的单选按钮

转载 作者:行者123 更新时间:2023-11-28 10:46:49 25 4
gpt4 key购买 nike

function validate()
{
var payment = checkRadio();
if (payment == false)
{
alert("Please select one button")
}
}

function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
else
{
return false;
}
}


}

下面的 html 代码创建单选按钮,供客户端选择一种付款方式

<P> Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
</P>

<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">

我的问题是,当我执行此代码并在 chrome 上运行它时,没有任何反应。如果有人能指出我哪里出错了,我将非常感激。

最佳答案

您需要将 html 代码用 <form> 括起来

<form>
Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal


<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
</form>

并在您的 javascript 中将 checkRadio 更改为:

function checkRadio()
{
var payment = document.getElementsByName('payment');

var paymentType = '';

for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
console.log(payment[i].value)
paymentType = payment[i].value;
}
}
return paymentType != '' ? true : false;
}

JSFiddle:https://jsfiddle.net/ttgrk8xj/16/

关于javascript - 验证 JavaScript 中的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com