简体   繁体   中英

Check multiple Checkbox jQuery

I have this code to get back a json string:

$.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

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

I have a PHP snippet like this

<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. But I think I have an error in my each part. But in the Firefox console is no error showing.

Could you help me?

Yes there is an issue in your $.each function.

 $.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

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.

You're using this selector to look for checkboxes:

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

However, the # symbol in a selector looks for an element with that ID .

The checkboxes in your PHP loop do not have a specified ID or class, so you could select them with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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