JQuery:Radiobutton没有正确选择相同的控件ID

问题描述:

我正在动态创建Radiobutton,并使用Jquery根据数据库中的值选择适当的单选按钮。以下是渲染后生成的示例代码。JQuery:Radiobutton没有正确选择相同的控件ID

<input checked="checked" id="Claim_0" name="Temp.MyClaim" type="radio" value="True" /> 
       <label for="Yes">Yes</label> 
       <input id="Claim_0" name="Temp.MyClaim" type="radio" value="False" /> 
       <label for="No">No</label> 

<input id="Claim_1" name="Temp.MyClaim" type="radio" value="True" /> 
       <label for="Yes">Yes</label> 
       <input checked="checked" id="Claim_1" name="Temp.MyClaim" type="radio" value="False" /> 
       <label for="No">No</label> 

我使用jQuery选择值,下面是示例代码

var j = 0; 
$('input:radio[id^="Claim_"]').each(function() { 

    var selection = $(this)[0].defaultChecked; 
    if (selection) {       
     if ($(this).val() == "True") { 
    $("input:radio[id=Claim_" + j + "]:nth(0)").attr('checked', true) 
      $('#ClaimData_' + j).show(); 
     } 
     else { 
    $("input:radio[id=Claim_" + j + "]:nth(1)").attr('checked', true) 
      $('#ClaimData_' + j).hide(); 
     } 
     j++; 
    } 
}); 

问题是,在页面的最终输出,只示出了最后一个单选按钮选中,我已经改变了每个组的动态ID,但仍然只有一个无线电正在被选中。

请提出我在做什么错,或者我该如何做到这一点。

+0

您使用LINQ到SQL(和textboxfor)? – ParPar

+0

所以如果值为True,应该检查,如果值不是True,它应该....等待....检查?看起来像没有每个()都有更简单的方法。 – adeneo

+1

即使条件'selection =='True''为false,你为什么会使复选框被“检查”? –

编辑这样

$('input:radio').each(function() { 

var selection = $(this).val(); 
if (selection == 'True') { 
    $(this).attr("checked", "checked"); 
} 
else { 
    $(this).attr("checked", "checked");   
} 
}); 
+0

与i ++有什么关系;? Does'nt each()是否已经有索引? – adeneo

+0

对不起,我编辑它。 – Gautam3164

+0

我把“Title”属性改为“title”,但没有运气。我不想遍历所有的单选按钮,但只是提供了“title”属性的地方,否则它会在if并为所有的单选按钮组。 – user1662589

$('input[type="radio"][title^="Claim_"]').prop('checked', true); 

您正在使用相同的名称和所有无线电的相同的ID,这样就会把事情搞得一团糟为您服务!

+0

是不是可以用单选按钮中的“title”属性来区分?我对这个属性很陌生。 – user1662589

+0

你应该使用唯一的ID或类来选择收音机,而不是标题。如果您为收音机使用相同的名称,则会成为一组单选按钮,在任何给定时间只能检查一个按钮。 – adeneo

+0

我正在使用MVC3和剃刀, – user1662589

对于所有的单选按钮,您都使用相同的名称Temp.MyClaim。这是一个单选按钮组,只能选择一个。