且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查Razor中的RadioButton是否已选中?

更新时间:2023-12-04 21:50:28

我不确定这是否是您的问题,但我认为您认为您有 name ="YesNo_ @ pNum" .我猜想 @pNum 是服务器端变量,输出是 name ="YesNo_X" .然后,在JS中,您有 $('[name ="YesNo_ @ placementNumber"] ,由于它不是 radio 的名称,因此将永远无法工作.

I'm not sure if this is your problem but I see that in your view you have name="YesNo_@pNum". I'm guessing that @pNum is a server side variable and the the output is name="YesNo_X". Then in the JS you have $('[name="YesNo_@placementNumber"], which will never work because that's not the name of the radio.

如果 placementNumber 是JS变量,则解决方案将使用以下方式更改选择器:

If placementNumber is a JS variable, the solution would be changing the selector with:

$('[name="YesNo_' + placementNumber + '"]:radio:checked')

如果您的JS中没有变量 placementNumber ,则可以向div中添加一个ID,包装收音机,然后选择它,如下所示:

If there is no variable placementNumber in your JS, you could add an id to the div wrapping the radios and then selecting it, like this:

<div class="YesNo" id="radios">
    <label><input type="radio" name="YesNo_@pNum" value="Yes" />@yesLabel</label>
    <label><input type="radio" name="YesNo_@pNum" value="No" checked />@noLabel</label>
</div>

然后获取检查值:

var checkedRadio = $('#radios :radio:checked').val();

我想您的另一件事可能是您希望在检查的单选更改时运行代码.我相信可能是因为:

The other thing I think your problem might be is that you want your code to run when the checked radio changes. I believe that might be it because of:

我看不到我的代码有效,因为在内存中总是选中否"

i dont see my code working because "No" is always checked in the memory

因此,您需要做的是:

$(function () {                       
    var radios = $('[name="YesNo_@placementNumber"]:radio');
    radios.on("change", function() {
        if ($(this).prop("checked")) {
            $("#sel").html("Selected Value: " + $(this).val());
        }
    });
});