【问题标题】:How to autoselect radio buttons in jQuery如何在jQuery中取消选择单选按钮
【发布时间】:2015-06-13 07:30:01
【问题描述】:

我有一个包含几行单选按钮的表单。当在第一行(仅第一行)中选择一个按钮时,我需要从上一个选择(向右)自动选择后续行,直到到达表格末尾。

单击第一行中的“MD”后,结果应如下所示: Desired Output

See JSFiddle Example Here

如果有意义的话,解决方案应该是基于相对位置的。唯一具有一致 ID 的元素是表格(“#skuTable”)。

到目前为止,我所拥有的是(控制台日志记录以进行调试):

$("#skuTable tr").first().find("input:radio").on("click", function(){
    var $this = $(this);
    console.log($this);
    console.log($this.position());
    console.log($this.parents("tbody").children("tr:nth-child(2)").find("input:radio").first().prop('checked', true));
});

设法做的是选择下一行的第一个单选按钮。我需要一些帮助来确定如何选择相对于第一个单选按钮的位置的下一个单选按钮。

【问题讨论】:

  • 如果有人选择了第一行的最后一个元素,你想做什么?
  • 在这个用例中根本不应该发生这种情况;但如果是,它不需要做任何事情。

标签: javascript jquery html


【解决方案1】:

我就是这样做的:

var rows = $("#skuTable tr");

rows.eq(0).find("input:radio").each(function(i) {
    $(this).on("click", function() {
        for(var m = 0, n = rows.length;m < n;m++) {
            rows.eq(m).find("input:radio").eq(i + m).attr("checked", true);
        }
    });                              
});

演示:https://jsfiddle.net/Lnk9p55x/4/

【讨论】:

  • 如果我在第一行选择4XL,然后选择M/S,结果不一致。
  • 所以你的意思是取消选中之前选中的单选按钮?
【解决方案2】:

另一种解决方案:

  $("#skuTable").find("input:radio").on("click", function(){
      loop = 0;
      $("input").prop("checked",false);
      index = $(this).parent().index("td");
      $.each($("table tbody tr"), function() {
          $("table tbody tr:eq("+loop+")").find("td:eq("+index+")").find("input:radio").prop('checked', true);
          index++;
          loop++;
      });
  });

https://jsfiddle.net/Lnk9p55x/7/

【讨论】:

    猜你喜欢
    • 2011-07-17
    • 1970-01-01
    • 2012-08-16
    • 2011-10-26
    • 2012-02-21
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 2015-07-01
    相关资源
    最近更新 更多