选中的单选按钮mvc4的值

时间:2013-10-16 10:21:31

标签: jquery asp.net-mvc-4

我正在研究MVC4项目。我遇到单选按钮问题。

这是radion按钮的HTML代码

@Html.RadioButton("Radiobtn", "true", new { id = "Radiobtn", @style = "width:auto;background:none;border:none" })
 Yes
 @Html.RadioButton("Radiobtn", "false", new { id = "Radiobtn", @style = "width:auto;background:none;border:none" })
 No

当我尝试通过jquery获取选定值时,我只能看到第一个单选按钮值。

这是jquery代码

$('#Radiobtn').click(function () {
            if ($(this).val() == 'true') {
                alert('true');
            } else if ($(this).val() == 'false') {
                alert('false');
            }
        });

现在仅在我选择第一个单选按钮时显示警报。第二个单选按钮点击没有发生什么?我不知道为什么它没有显示警报?

5 个答案:

答案 0 :(得分:0)

$('.Radiobtn').click(function () { //add class on each radiobutton here i take "Radiobtn"
            if ($(this).val()) {
                alert('true');
            } else {
                alert('false');
            }
        });

答案 1 :(得分:0)

删除重复的ID并尝试以下操作:

$('input[name=RadioBtn]').on('click', function() {
    // whatever...
});

答案 2 :(得分:0)

两个单选按钮都不能有id。最好使用 class (但我更喜欢使用群组名称)和 change 事件处理程序。

$('.Radiobtn').change(function () {
            if ($(this).val() == 'true') {
                alert('true');
            } else if ($(this).val() == 'false') {
                alert('false');
            }
        });

答案 3 :(得分:0)

您正在复制id属性,这是无效的,这就是jQuery仅在点击第一个无线电时工作的原因。尝试使用class,如下所示:

@Html.RadioButton("Radiobtn", "true", new { id = "YesRadio", @class = "radio", @style = "width:auto;background:none;border:none" })
Yes

@Html.RadioButton("Radiobtn", "false", new { id = "NoRadio", @class = "radio", @style = "width:auto;background:none;border:none" })
No
$('.radio').click(function () {
    if ($(this).val() == 'true') {
        alert('true');
    } 
    else if ($(this).val() == 'false') {
        alert('false');
    }
});

答案 4 :(得分:0)

给你的单选按钮提供一个类,同时它们也应该有不同的ID。

@Html.RadioButton("RadiobtnYes", "true", new { class= "Radio", @style = "width:auto;background:none;border:none" })
 Yes
 @Html.RadioButton("RadiobtnNo", "false", new { class= "Radio", @style = "width:auto;background:none;border:none" })
 No

$(".Radio").click(function(){
alert(this.val());
})

根据点击的单选按钮,它会提醒truefalse

相关问题