0

我有一个 ASPX 页面,在页面加载中我动态创建一些单选按钮列表控件并呈现给浏览器。我将在每个单选按钮列表中有 2 个列表项。一个是是,第二个是否。单选按钮列表的数量可以是 n.Now 在我的 java 脚本代码中,我想知道单击了哪个单选按钮。我已经在使用 jQuery 了。有什么简单的方法来处理这个问题吗?

我呈现给浏览器的 HTML 是

<table border="0" id="tblQuestions">
    <tr>
        <td>Do you have a valid passport ?</td>
    </tr><tr>
        <td><table id="answer-1" border="0">
            <tr>
                <td><input id="answer-1_0" type="radio" name="answer-1" value="1" /><label for="answer-1_0">Yes</label></td>
            </tr><tr>
                <td><input id="answer-1_1" type="radio" name="answer-1" value="0" /><label for="answer-1_1">No</label></td>
            </tr>
        </table></td>
    </tr><tr>
        <td>Are you married ?</td>
    </tr><tr>
        <td><table id="answer-2" border="0">
            <tr>
                <td><input id="answer-2_0" type="radio" name="answer-2" value="1" /><label for="answer-2_0">Yes</label></td>
            </tr><tr>
                <td><input id="answer-2_1" type="radio" name="answer-2" value="0" /><label for="answer-2_1">No</label></td>
            </tr>
        </table></td>
    </tr>
</table>

提前致谢

4

2 回答 2

3

以下代码并未具体回答您的问题,但它可能会有所帮助。我会为你修改它,但我现在没有时间。

我在考试中使用它,以警告用户某个特定问题没有选定的答案。

这些问题是使用发出普通 xhtml 的服务器控件动态生成的。我用相同的名称命名所有选项,(Q1,Q2...),并将它们标识为(Q1a,Q1b ...)

为了根据您的目的对其进行修改,也许您可​​以在 j 循环中构建一个选定选项的列表,即在“break”语句所在的位置添加名称-值对。

// Grabs all inputs - radio, checkbox, text, buttons and lists -sticks them in an array
allInputs = document.getElementsByTagName("input");
var last = "NameUnlikelyToBeUsedAsAnElementName";

// walk through the array
for (i = 0; i< allInputs.length; i++)
{
    var input = allInputs[i];
    if (input.name == last) continue; // if this object name is the same as the last checked radio, go to next iteration


    // checks to see if any  one of  similarly named radiobuttons is checked 
    else if (input.type == "radio" )
    {    
        last = input.name;  
        var radios = document.getElementsByName(input.name);
        var radioSelected=false;

         //iterate over question options
        for (j=0; j < radios.length; j++)
        {
            if(radios[j].checked)
            {
               radioSelected=true;
               break; // Found it, proceed to next question 
            }
        }
        if (!radioSelected) // no option selected
        {       // warn user, focus question
            alert("You did not answer question " + input.id.substring(0,input.id.length-1));
            input.focus();
            return false;
        }                   
    }

}

return true;
于 2009-05-27T13:27:18.113 回答
0

这是假设您的页面中已经包含 jquery。

在您的单选按钮项目上定义一个类,基本上您的客户端 HTML 应该看起来像<input id="answer-2_1" type="radio" name="answer-2" value="0" class="myrdo" />

现在,在您的 js 代码中,只需在类上连接一个事件处理程序

$(".myrdo").bind("click",function(){if($(this).attr("checked")==true) {alert($(this).val);} });

上面的命令将简单地提醒所选单选按钮的值。

于 2009-05-27T11:38:33.620 回答