0

I have the following script that is supposed to check and uncheck the following html form based on the user name that has been picked from the dropdown :

<div>
    <select name="user_name" id="user_name" class="user_name form-control">
        <option>Please select : </option>
        <?php foreach ($system_users as $value) {
            ?>
            <option value="<?php echo $value['id']; ?>"><?php echo $value['user_name']; ?></option>
            <?php
        }
        ?>
    </select>
</div>

<?php foreach ($reports_functions as $value) {
    ?>
    <input type="checkbox" name="functions[]" id="functions" value="<?php echo $value['id']; ?>"  class="form-control functions reports_functions" /> <?php echo $value['name']; ?>
    <hr>
    <br />

    <?php
}
?>

The following is my jquery script :

$("#user_name").change(function () {
    var user_id = this.value;
    $.ajax({
        type: "GET",
        url: "<?php echo base_url(); ?>admin/get_user_permissions/" + user_id,
        dataType: "JSON",
        success: function (response) {
             $("input:checkbox").attr("checked", false);

            for (i = 0; i < response.length; i++) {
                var value = response[i].function_id;
                $("input:checkbox[value=" + value + "]").attr("checked", true);
            }
        }
    });
});

The problem I'm having is when I select a username , the check box are not checked because of the line : $("input:checkbox").attr("checked", false); but when I remove it , it checks them but does not remove the previously checked checkboxes. How can I solve this issue?

1
  • use .prop("checked",true) instead of .attr(.. Commented Oct 22, 2015 at 11:50

2 Answers 2

2

You have to use prop() instead of attr(). Change the code to:

$("input:checkbox[value=" + value + "]").prop("checked", true);
Sign up to request clarification or add additional context in comments.

2 Comments

If you have a look at this: jQuery Blog, which says the release of new jQuery 1.6.1, they have changed the way .attr() handles boolean values.
Okay. Now making sense. Always care to explain the reason for changes in OP codes. That makes a lot sense. Mere code is not an answer.
1

Use prop instead of attr. Change the code to:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.