使用JQuery设置单选按钮的值(ASP.NET MVC)

时间:2010-03-25 14:10:54

标签: jquery asp.net-mvc

我在所有列表中都有(4)单选按钮{value =“0”,“1”,“2”,“3”}的2个“列表”。 第一个列表需要驱动第二个列表(可能多次出现)。因此,如果在第一个列表中选择了一个选项,则会在第二个列表中选择SAME选项。这听起来很奇怪,但它有一个目的。第一个列表更多是“全选”类型的列表,第二个列表是单个选择列表。

我通过JQuery获得“selectall”列表的值:

$("#selectalllist").change(function() {
    var str = $('input[name=selectall]:checked').val();
    $(".radiolist").attr('checked', str);   //This is my thinking
});

当前选中的值存储在str变量中,这看起来是正确的(我使用alert来告诉我存储的是什么,它出现了我的预期)。我只需要设置下一组列表的值。我认为代码的第二行会将$(“。radiolist”)的检查值设置为存储值,但它总是将值设置为最后一个条目(value =“3”)。

我想知道.attr('',str)调用中是否有错误的属性?有什么想法吗?

根据要求:

(选择所有按钮)

<input type="radio" id="radCurrent" name="selectall" value="0" /><label for="radCurrent">Current</label>
<input type="radio" id="radFuture" name="selectall" value="1" /><label for="radFuture">Future</label>
<input type="radio" id="radCurrentAll" name="selectall" value="2" /><label for="radCurrentAll">CurrentAll</label>
<input type="radio" id="radFutureAll" name="selectall" value="3" /><label for="radFutureAll">FutureAll</label>

(列表按钮)

<input type="radio" name="selectvalue" id="Current" value="0" class="radiolist" /> C
<input type="radio" name="selectvalue" id="Future" value="1" class="radiolist" /> F
<input type="radio" name="selectvalue" id="CurrentAll" value="2" class="radiolist" /> CA
<input type="radio" name="selectvalue" id="FutureAll" value="3" class="radiolist" /> FA

2 个答案:

答案 0 :(得分:1)

您需要选择

选项
$("#selectall").change(function() {
    var str = $('#selectall:checked').val();
    $(".radiolist[value='" + str + "']").attr("checked", "checked");
});

答案 1 :(得分:1)

要做到这一点,你需要一个稍微不同的方法,基于你发布的html:

$("input[name=selectall]").change(function() {
  var str = $('input[name=selectall]:checked').val();
  $(".radiolist[value='" + str + "']").attr("checked", true);
});

这里有一些变化:

  • 输入有一个名称,而不是selectall的ID,因此需要选择。
  • attr("checked", true)可以是true / false(而不是值),有跨浏览器检查来处理j?内部查询。
  • 对于设置,您还需要抓住所需的单选按钮并进行检查。他们在同一组中的事实将使浏览器取消选中之前的选择。