0

如果没有选中任何单选框,则返回 0,如果选中,则返回选中的值

<div class="radiogroup">A.
    <input type="radio" name=a1 value="1">$item[2]
    <br/>B.
    <input type="radio" name=a1 value="2">$item[3]
    <br/>C.
    <input type="radio" name=a1 value="3">$item[4]
    <br/>D.
    <input type="radio" name=a1 value="4">$item[5]
    <br/>E.
    <input type="radio" name=a1 value="0">Not sure
    <br/>
</div>
<div class="radiogroup">A.
    <input type="radio" name=a2 value="1">$item[2]
    <br/>B.
    <input type="radio" name=a2 value="2">$item[3]
    <br/>C.
    <input type="radio" name=a2 value="3">$item[4]
    <br/>D.
    <input type="radio" name=a2 value="4">$item[5]
    <br/>E.
    <input type="radio" name=a2 value="0">Not sure
    <br/>
</div>
<div class="radiogroup">A.
    <input type="radio" name=a3 value="1">$item[2]
    <br/>B.
    <input type="radio" name=a3 value="2">$item[3]
    <br/>C.
    <input type="radio" name=a3 value="3">$item[4]
    <br/>D.
    <input type="radio" name=a3 value="4">$item[5]
    <br/>E.
    <input type="radio" name=a3 value="0">Not sure
    <br/>
</div>

这是我的代码:

$(function () {
    $("#submit").click(function () {
        var arr = new array();
        var k = 0;
        $(".radiogroup").each(function () {
            if ($(this."input:radio:checked").length == 0) {
                arr[k++] = 0;
            } else {
                arr[k++] = $(this."input:radio:checked").val();
            }
        });
        return false;
    });

});

我坚持的是我不知道如何使用“this”来选择 div 包装器中的无线电组,例如,如果我需要提醒每个检查的值,我想这样做,它没有虽然工作:

$(".radiogroup").each(function () {
    alert($(this.input: radio: checked).val());

});

在最终生成 html 代码之前,radio group 的数量是不确定的,所以 name=a1,name =a2 停止到一个我什至不知道的数字,这意味着不可能在循环中使用 name 作为变量

我需要在每个 div 包装器中选择选中的单选框,每个单选都没有 id,该怎么做呢?

4

3 回答 3

2

你需要改变

 if ($(this."input:radio:checked").length == 0) {

 if ($(this).find("input[type=radio]:checked").length == 0) {

arr[k++] = $(this."input:radio:checked").val();

arr[k++] = $(this).find("input[type=radio]:checked").val();
于 2013-06-26T20:58:22.940 回答
1

You need to change the lines that say

$(this."input:radio:checked")

to

$(this).find("input[type='radio']:checked"

and

var arr = new array();

to either one of the following:

var arr = new Array();
var arr = [];

That'll fix it.

Here is a fiddle that has a working example.

于 2013-06-26T21:02:43.857 回答
0

你可以做:

$(".radiogroup").each(function() {
    console.log($(this).children("input[type='radio']:checked").val());
});
于 2013-06-26T20:55:55.660 回答