问题描述
我想检查是否有任何单选按钮被选中,如果没有选择打印一些警告信息。
I want to check is there any radio button selected and if there is no selection to print some alert message.
html代码是:
<form action="" id="form" name="form" method="post">
<input type="radio" id="form_rd" name="form_rd" value="1"> 1
<input type="radio" id="form_rd" name="form_rd" value="2"> 2
<input type="radio" id="form_rd" name="form_rd" value="3"> 3
<button type="submit">send</button>
</form>
我用来检查的Jquery:
Jquery that I'm using for checking:
$("form#form").submit(function() {
if (!$("#form_rd").attr('checked')) {alert("not checked");return false;}
})
此jquery代码不管用。这个单选按钮检查有什么更好的解决方案?
This jquery code is not working. What is the better solution for this radio button check?
推荐答案
我无法强调 ID 必须独一无二!因此,将 id =form_rd
更改为(例如) class =form_rd
。但是,单独留下 name
,因为如果您更改了该请求,接收端也不会喜欢该请求。
I cannot emphasize enough that IDs must be unique! So change your id="form_rd"
into (for example) class="form_rd"
. Leave name
alone, however, because the receiving end won't like the request if you change that too.
尝试
$("form#form").submit(function() {
if ($("#form :radio:checked").length == 0) {
alert("not checked");
return false;
}
});
如果您有多个组,这将失败。你需要一个解决方案吗?
This will fail if you have multiple groups. Do you need a solution for that?
这篇关于Jquery单选按钮检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!