繁体   English   中英

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

[英]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,我想要一个警告说“新”,否则什么都没有。

通常它很容易,因为你有id但在这种情况下没有ID?

因为这是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");

                    }

                });


            }

        });

这是有效的,但如果单选按钮在页面加载它不起作用,我必须单击另一个单选按钮,然后单击“新”,然后它将工作..

任何机会,如果它已经检查已经检查,而不是检查。

@ 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的情况下实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM