如果选择单选按钮显示警报

If radio button is selected show alert

我希望在单击单选按钮时显示提醒。

我的单选按钮:

<div class="genericFormField">
   New:@Html.RadioButtonFor(m => m.Form.InstallType, 1, Model.InstallationHeader.InstallType == 1 ? new { Checked = "checked" } : null )
   Pool:@Html.RadioButtonFor(m => m.Form.InstallType, 2, Model.InstallationHeader.InstallType == 2 ? new { Checked = "checked" } : null)
   Refurb:@Html.RadioButtonFor(m => m.Form.InstallType, 3, Model.InstallationHeader.InstallType == 3 ? new { Checked = "checked" } : null)              
</div>

因此,如果选择了新的单选按钮,我想提醒说 "NEW" 否则什么也没有。

通常情况下很容易,因为你有身份证,但这次没有身份证?

因为这是 RadioButtonFor。

谢谢

新密码

完整代码:

       $('input[name="Form.InstallType"]').on('change', function() {
            var val = $('input[name="Form.InstallType"]:checked').val();
            if (val === '1') {

                var validOptions = "@Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val();
                previousValue = "";

                $('#abc').autocomplete({
                    autoFocus: true,
                    source: validOptions,

                }).change(function(){

                    var source = validOptions;
                    var found = $('.ui-autocomplete li').text().search(source);
                    console.debug('found:' + found);
                    var val = $('input[name="Form.InstallType"]:checked').val();

                    if (found < 0 && val === '1') {
                        $(this).val('');
                        alert("Please choose from auto complete");

                    }

                });


            }

        });

这行得通,但是如果单选按钮在页面加载时它不起作用,我必须单击另一个单选按钮,然后单击 "new" 然后它就会工作..

如果它已经检查而不是检查时,它可能会起作用。

@Html.RadioButtonFor 使用 nameid 属性创建一个适当的 input

您可以通过这种方式访问​​值:

$('input[name="Form.InstallType"]:checked').val();

不确定生成的收音机的名称,因为它是一个内部变量。
呈现页面并查看生成的名称。这就是我的情况。

现在,关于您的警报。您需要收听 change 事件。

$('input[name="Form.InstallType"]').on('change', function()
{
    var val = $('input[name="Form.InstallType"]:checked').val();        
    if (val === '1') alert('New');
});

为什么是“1”?因为你已经在ASP.NET代码中设置了。 它应该是这样的。

<div class="genericFormField">
   New: @Html.RadioButtonFor(m => m.Form.InstallType, 'new')
   Pool: @Html.RadioButtonFor(m => m.Form.InstallType, 'pool')
   Refurb: @Html.RadioButtonFor(m => m.Form.InstallType, 'refurb')              
</div>
<script>
    $(document).ready(function() {
        AlertIfNewIsSelected(); // Check if it is selected on page load. According to the question in comments.
        $('input[name="Form.InstallType"]').on('change', AlertIfNewIsSelected);
    });

    function AlertIfNewIsSelected()
    {
        var val = $('input[name="Form.InstallType"]:checked').val();        
        if (val === 'new') alert('New');
    }
</script>

当然,不用jQuery也能达到。