使用jQuery获取单选按钮的当前选定值

| 在MVC中,我可以定义一组单选按钮,如下所示:
@Html.RadioButtonFor(x => x.hasAcceptedAgreement, true) Yes
@Html.RadioButtonFor(x => x.hasAcceptedAgreement, false) No
呈现
<input id=\"hasAcceptedAgreement\" name=\"hasAcceptedAgreement\" type=\"radio\" value=\"True\" /> Yes
<input id=\"hasAcceptedAgreement\" name=\"hasAcceptedAgreement\" type=\"radio\" value=\"False\" /> No
我想根据选择的项目来禁用或启用div,我已经使用以下jQuery做到了这一点:
$(\':radio[name=hasAcceptedAgreement]\').change(function () {
    if ($(this).val() == \'True\') {
        // display div
    } else {
        // hide div
    }
});
但是,当他们提交表单时,我还需要进行检查以查看当前选择了哪个值,然后再次显示/隐藏相应的部分(因为在POST上不会调用.change函数)。我有办法做到吗? 如果我尝试执行$(\':radio [name = hasAcceptedAgreement] \')。val(),由于ID相同(我假设),它将始终评估为True。还有其他获取值的方法吗,还是因为MVC喜欢为每个id赋予相同的名称,所以我不愿意这样做吗? 编辑:顺便说一下,我知道我可以在RadioButtonFor调用中手动设置ID-我只是想知道是否有一些更简单的内置方法来处理我不知道的事情。     
已邀请:
        就像他们在这里说的那样:如何获取通过jQuery选择的收音机?您可以使用:
$(\'input[name=hasAcceptedAgreement]:checked\').val()
获取当前所选收音机的值。     
        我在下面的项目中使用了下面的代码,它确实起作用了!
$(\':radio[name=hasAcceptedAgreement]\').change(function () {
    if ($(\'input[name=hasAcceptedAgreement]:checked\').val() == \'True\') {
        // display div
    } else {
        // hide div
    }
});
    
        
$(function(){
   // executed once the dom is loaded

   // bind the change function as usual
   $(\':radio[name=hasAcceptedAgreement]\').change(function () {
        if ($(this).val() == \'True\') {
            // display div
        } else {
            // hide div
        }
    }).change();  // and immediately trigger it
});
变更处理程序的一个小改进(因此您不需要if / else块)
$(\"#yourdiv\").toggle( $(this).val() == \'True\' );
    

要回复问题请先登录注册