【问题标题】:How to set checkbox checked using jquery?如何设置使用jquery检查的复选框?
【发布时间】:2021-09-28 07:16:57
【问题描述】:

嘿,我是 Web 开发新手,目前正在从事基于 laravel 框架的项目。这是我的代码,显示所有复选框并根据数据库值检查它们,但我在 jquery 方面感到困惑

Html 刀片代码:

@foreach ($param as $value)
<input type="checkbox" name="param1[]" id="param1" value="{{$value->id}}"
    <label>&nbsp;{{$value->parameters}}</label><br>
@endforeach

这里的值为1,2,3,4,5 来自 db 的数据是1,2,3 所以只检查那些

这是我的 Jquery 代码:

$(".edit").click(function() {

  $("#exampleModal1").modal('show');

  $tr = $(this).closest('tr');
  var data = $tr.children("td").map(function() {
    return $(this).text();
  }).get();
  $("#sub").val(data[2]);
  id = data[0];
  var _token = $('input[name="_token"]').val();
  console.log(_token);
  $.ajax({
    url: "{{route('admin.getparam')}}",
    type: "post",
    data: {
      "cp_id": data[1],
      "_token": _token
    },
    success: function(response) {
      var arr = $.parseJSON(response);
      //alert(arr);
      $.each(arr, function(i, v) {
        alert($('#param1').val());
        //alert(v);
      });
    }
  });
});

我需要代码来只选中那些复选框 请帮忙

【问题讨论】:

  • 这能回答你的问题吗? Setting "checked" for a checkbox with jQuery
  • 我看到您在所有foreach 中都使用相同的 ID - 在 JS 中永远无法使用,因为 ID 必须是唯一的
  • 为什么你的$.each() 循环不使用iv
  • @Barmar 您的代码不起作用
  • 你能说得更具体点吗?您是否尝试过对其进行任何调试?数组是来自 DB 整数还是字符串?您显示了整数,所以我在调用 .includes() 之前将复选框值转换为整数。

标签: jquery laravel-blade


【解决方案1】:

遍历复选框,根据值是否在返回的 JSON 数组中,选中或取消选中它们。

$.ajax({
  url: "{{route('admin.getparam')}}",
  type: "post",
  data: {
    "cp_id": data[1],
    "_token": _token
  },
  dataType: 'json',
  success: function(arr) {
    let checkboxes = $('input[name="param1\\[\\]"]');
    checkboxes.prop('checked', (i, cb) => arr.includes(+cb.value));
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 2013-09-03
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多