0

I have a javascript's script which allow to check 2 checkboxes with the same values at the same time but it doesn't work.

I get the values from a databases thanks to a php's foreach loop. Here is my test code:

    <?php
            //checkboxes
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
           //script
           foreach($host1 as $row){ ?>
            <script type="text/javascript">
           var $checkboxes = $("input[type=checkbox][name='list[]'][value='<?php echo $row['table']?>']");
                $checkboxes.on("click", function() {
                var checkedState = this.checked
                $checkboxes.each(function() {
                    this.checked = checkedState;
            });
           });
            </script>
<?php    }

If I change the value $row['table'] into a simple number, "2" for example, it's working. I also look if the values ($row['table']) of every checkboxes are the same and they are all good.

Strange thing : When I check any checkboxes, it will not check the corresponding ones, but it will instead check the lasts of the table.

Any ideas where is my mistake ?

Thank you ;)

9
  • 2
    Are you sure you want your javascript to be added within a PHP loop? You're adding the same JS n number of times. Commented Mar 31, 2017 at 14:13
  • Why do you have two php foreach loops? The point of a foreach is that you use one to loop through EACH item. Commented Mar 31, 2017 at 14:14
  • why don't you use class attribute in input type checkbox? Commented Mar 31, 2017 at 14:14
  • What is that javascript doing? You've got a loop so checkboxes is getting overwritten with each interaction. You're also binding to that event multiple times but since you're outputting it all with PHP in the end it only gets bound once. Commented Mar 31, 2017 at 14:16
  • If you add the rendered html to an example on jsfiddle.net, it'll probably become apparent to us what your problem is very quickly. Commented Mar 31, 2017 at 14:17

2 Answers 2

2

You should try this. I think this is what you want

<?php
//checkboxes
foreach ($host1 as $row) {
    echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
foreach ($host1 as $row) {
    echo'<input class="my_cb" type="checkbox" name="list[]" value="' . $row['table'] . '"/>';
}
//script
?>
<script type = "text/javascript">
    $(document).ready(function () {

        $(".my_cb").on("click", function () {
            var val = $(this).val();
            var checkboxes = $("input[type=checkbox][name='list[]'][value='"+val+"']");
            var checkedState = this.checked;
            checkboxes.each(function () {
                this.checked = checkedState;
            });

        });
    });
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

The problem in your code is with $checkboxes variable. Everytime foreach runs, it overrides its value. Thats why it checks only last checkbox in the end.
You can replace $(".my_cb").on( with $("input[type=checkbox][name='list[]']").on( if you don't want to use a class
Wow, thank you it's working ! The problem solved when I added $(document).ready(function () ). I will use your code tho since it doesn't use a php's loop and more easy to understand. Thanks ;)
2

Instead of doing a php loop and assigning each click event separately, let jQuery handle that:

// this selector should get all your checkboxes
var checkboxes = $("input[type=checkbox][name='list[]']");

checkboxes.click(function() {
     // not sure what you are trying to do here but it just looks like you are trying to set all checkboxes to the same state as the current one
     checkboxes.prop('checked', this.checked);
});

Update

As you only have 2 list of checkboxes with the same name, I have shown options for if they have different parent elements or the same parent element

JS:

var list = $('.parent-element').find("input[type=checkbox][name='list[]']"),
    list1 = $('.parent-element1').find("input[type=checkbox][name='list[]']");

list.click(function() {
  var checkbox = $(this),
      thisIndex = list.index(checkbox);

   list1.eq(thisIndex).prop('checked', this.checked);

   // if at all possible I would use the above index to change the corresponding checkbox in the other list.

   // if all checkboxes are under the same parent then you will only have list (list1 won't be needed) 
   // and it will contain all children so to get the corresponding index you would need to do:

   var thisIndex = list.index(checkbox) + (list.length / 2);
   list.eq(thisIndex).prop('checked', this.checked);

});

6 Comments

Hey, I don't want to check all of them. I want to check them by values, so 2 at the same time for my code example. This is why I need the foreach loop, because the value is from a db
I'm guessing you haven't written your loops correctly then, does the second checkbox list have a different name?
No same name, the problem come when I use an array.
Could be the values you're pulling from the database are not what you think, have you tried a var_dump()?
so your going to be using the same name checkbox and posting the same value twice? Doesn't make any sense, also what happens if other checkboxes has the same value so you may end up with 4 checkboxes with the same value? Are these checkbox lists on different parts of your page with different parent elements?
|

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.