【问题标题】:Check checkbox based on ajax response根据ajax响应检查复选框
【发布时间】:2018-06-25 02:18:42
【问题描述】:

我有一个包含许多此类复选框的表单:

<label class="checkbox">
<input type="checkbox" id="user_ids_for_edit" name="user_ids_for_edit[]" data-toggle="checkbox" data-toggle="checkbox" value="14">Billy Joel
</label>

表单是模式的一部分。

当模式加载时,我运行一个 ajax 查询来检查复选框,基于 ajax 查询的结果:

$.ajax({
   type: "GET",
   url: "/data/team_users",
   data: { id: data.id },
   cache: false,
   dataType: "json",
   success: function(response)
      {
        for (var user in response) {
            alert(response[user].id); // this gives the right user id, so my ajax call works... 
            $('#user_ids_for_edit[value="'+ response[user].id +'"]').attr('checked', true);
        }

      }
});

很遗憾,相关的复选框没有被选中。我不知道如何进一步进步。任何帮助将不胜感激。

【问题讨论】:

  • 你可以这样检查吗? $('#user_ids_for_edit').val(response[user].id).attr('checked', true);
  • 如果您有多个复选框,那么每个复选框都应该具有相同的名称但不同的 id,您的代码不起作用,因为您的所有元素(复选框)都有保存 id
  • 虽然从 1.6 开始您应该使用 prop() 是正确的,但即使使用 attr(),您的代码也应该可以正常工作它在 sn-p 中工作正常以进行测试。此外,虽然您有多个具有相同标识符的元素,这是糟糕的设计,但同样,您的代码在 sn-p 中运行良好,并且当您使用属性选择器和标识符时,所有具有相同标识符的复选框都会被检查。 jsfiddle.net/gwuoyoxv
  • 谢谢。我只是让ID独一无二。并尝试了建议道具而不是 attr。但是,复选框仍然没有被选中。
  • @AdamDulson 正如我所说并在 js fiddle 中展示的那样,您的代码工作得很好,即使不遵守标准但无论哪种方式问题似乎都是其他问题

标签: javascript jquery ajax checkbox


【解决方案1】:

你可以试试这个而不是 attr

prop('checked', true);

【讨论】:

  • 虽然prop 是首选,但attr 的工作原理相同,不是问题的根源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多