简体   繁体   English

检查多个Checkbox jQuery

[英]Check multiple Checkbox jQuery

I have this code to get back a json string: 我有以下代码来获取json字符串:

$.getJSON("<?php echo BASE_URL; ?>/editTask.php?ID="+tid,function(result){
        $.each(result.staff, function() { 
            $("#checkbox[value=" + this + "]").prop('checked');
        });
});

The json looks like this json看起来像这样

{"staff":[13,17,15]}

I have a PHP snippet like this 我有这样的PHP代码段

<div id="checkbox" class="checkbox" style="max-height:150px;overflow:auto;">
<?php
for ($i = 0; $i < count($user_list); ++$i) {
  echo '<label>'
      .'<input type="checkbox" name="tasksUser[]" 
           value="'.$user_list[$i]['uid'].'">'
      .$user_list[$i]['surname'].', '.$user_list[$i]['forename']
      .'</label><br />';
}
?>
</div>

I want that every checkbox that has the value that is in result.staff be checked. 我希望选中具有result.staff中的值的每个复选框。 But I think I have an error in my each part. 但是我认为我的每个部分都有一个错误。 But in the Firefox console is no error showing. 但是在Firefox控制台中没有错误显示。

Could you help me? 你可以帮帮我吗?

Yes there is an issue in your $.each function. 是的,您的$ .each函数中存在问题。

 $.each(result.staff, 
     function() { 
         $("#checkbox[value=" + this + "]").prop('checked');
            ^
            Here is the issue.
     });
 });

As you don't have any id or class associated with element you can access it using element name/+type 由于您没有与元素相关联的任何ID或类,因此可以使用元素名称/类型来访问它

You must replace your code with 您必须将代码替换为

$("input[type='checkbox'][value=" + this + "]").prop("checked", true);

Here I am accessing all checkboxes with values available and setting checked as true. 在这里,我将访问所有具有可用值并将值设置为true的复选框。

You're using this selector to look for checkboxes: 您正在使用此选择器查找复选框:

$("#checkbox[value...]")

However, the # symbol in a selector looks for an element with that ID . 但是,选择器中的#符号将查找具有该ID的元素。

The checkboxes in your PHP loop do not have a specified ID or class, so you could select them with: PHP循环中的复选框没有指定的ID或类,因此可以通过以下方式选择它们:

#(":checkbox[value...]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM