10

I am new to PHP. I want to create a script to check all checkboxes in a row, but I am stuck.

PROBLEM

Code is not working with loop.

Here is my output

enter image description here

When I check the checkbox under the Opinion column I want to automatically check all checkboxes in the same row.

Here is my code

To render data and checkboxes for each row I use a server-side PHP loop

JavaScript:

<script>      
$('.allcb').on('click', function() {
    $(this).parent().parent().parent().parent().find('.chk').prop('checked', this.checked);
});
</script>

HTML:

 <?php
        for ($i=0; $i<count($opinion); $i++) {
    //if ($opinion[$i] == "")continue;
        ?>
          <tr>
            <td>
               <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
             <!-- <input type="text" name="opinion[]" value="<?php //echo $opinion[$i]?>" size="28" readonly="readonly" />-->

      <input type="checkbox" name="opinion[]" class="allcb" data-child="chk" value="<?php echo $opinion[$i]?>" />
      <?php echo $opinion[$i]?>
    </td>
    <td>
      <input type="checkbox" name="action[]" class="chk" value="<?php echo $action[$i] ?>" />
      <?php echo $action[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="long_term[]" class="chk" value="<?php echo $long_term[$i] ?>" />
      <?php echo $long_term[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="p_long_term[]" class="chk" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
      <?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
    </td>
    <td>
      <input type="checkbox" name="short_term[]" class="chk" value="<?php echo $short_term[$i] ?>" />
      <?php echo $short_term[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="p_short_term[]" class="chk" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
      <?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
    </td>
    <td>
      <input type="checkbox" name="outlook[]" class="chk" value="<?php echo $outlook[$i] ?>" />
      <?php echo $outlook[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="rating_type[]" class="chk" value="<?php echo $rating_type[$i] ?>" />
      <?php echo $rating_type[$i] ?>
    </td>
  </tr>
<?php
        }
?>
7
  • 4
    $(this).closest('tr').find('.chk').prop('checked', this.checked); select all checkbox with class chk in same row Commented Nov 3, 2015 at 10:27
  • 1
    Are the rows dynamically added? Commented Nov 3, 2015 at 10:29
  • @fuyushimoya i used loop to print my data in row Commented Nov 3, 2015 at 10:30
  • Then check the console, is it complain that $ is undefined or something? or this <script> appears at head? It'd be better to wrap that function in a domready to ensure the target elements exist. Commented Nov 3, 2015 at 10:34
  • @fuyushimoya Everything is running fine, I have just issue in Chkboxes Commented Nov 3, 2015 at 10:44

7 Answers 7

3
+50

A simple way would be if you add some identifier to you TRs so the checkbox "knows" which checkboxes are in the same row.

It would also be possible by checking the parent nodes but this may be a bit unstable (think about restructure the table for example).

function toggleRowCbs(cb) {
  var cbs = document.getElementById(cb.dataset.rowid).querySelectorAll('[type="checkbox"]');
  [].forEach.call(cbs, function(x) {
    x.checked = cb.checked;
  });
}
table,
tr,
td,
th {
  border: 1px solid #ccc;
  border-collapse: collapse;
  text-align: left;
  padding: 2pt 4pt;
}
<table>
  <tr>
    <th>Optionion</th>
    <th>Action</th>
    <th colspan="4">Ratings</th>
    <th>Outlook</th>
    <th>Rating Type</th>
  </tr>
  <tr>
    <th></th>
    <th></th>
    <th colspan="2">Long Term</th>
    <th colspan="2">Short Term</th>
    <th></th>
    <th></th>
  </tr>
  <tr>
    <th></th>
    <th></th>
    <th>Current</th>
    <th>Previous</th>
    <th>Current</th>
    <th>Previous</th>
    <th></th>
    <th></th>
  </tr>
  <tr id="row1">
    <td>
      <input type="checkbox" data-rowid="row1" onchange="toggleRowCbs(this)" />Foobar
    </td>
    <td>
      <input type="checkbox" />Maintain
    </td>
    <td>
      <input type="checkbox" />A+
    </td>
    <td>
      <input type="checkbox" />A+
    </td>
    <td>
      <input type="checkbox" />A1
    </td>
    <td>
      <input type="checkbox" />A1
    </td>
    <td>
      <input type="checkbox" />Stable
    </td>
    <td>
      <input type="checkbox" />Entity
    </td>
  </tr>
  <tr id="row2">
    <td>
      <input type="checkbox" data-rowid="row2" onchange="toggleRowCbs(this)" />Foobar #2
    </td>
    <td>
      <input type="checkbox" />Maintain
    </td>
    <td>
      <input type="checkbox" />A+
    </td>
    <td>
      <input type="checkbox" />A+
    </td>
    <td>
      <input type="checkbox" />A1
    </td>
    <td>
      <input type="checkbox" />A1
    </td>
    <td>
      <input type="checkbox" />Stable
    </td>
    <td>
      <input type="checkbox" />Entity
    </td>
  </tr>
</table>

So your PHP Code would look like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<?php
    for ($i=0; $i<count($opinion); $i++) { ?>
      <tr id="row<?php echo $i ?>">
        <td>
      <input type="checkbox" data-rowid="row<?php echo $i ?>" onchange="toggleRowCbs(this)" name="opinion[]" class="allcb" data-child="chk" value="<?php echo $opinion[$i]?>" />
      <?php echo $opinion[$i]?>
    </td>
    <td>
      <input type="checkbox" name="action[]" class="chk" value="<?php echo $action[$i] ?>" />
      <?php echo $action[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="long_term[]" class="chk" value="<?php echo $long_term[$i] ?>" />
      <?php echo $long_term[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="p_long_term[]" class="chk" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
      <?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
    </td>
    <td>
      <input type="checkbox" name="short_term[]" class="chk" value="<?php echo $short_term[$i] ?>" />
      <?php echo $short_term[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="p_short_term[]" class="chk" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
      <?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
    </td>
    <td>
      <input type="checkbox" name="outlook[]" class="chk" value="<?php echo $outlook[$i] ?>" />
      <?php echo $outlook[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="rating_type[]" class="chk" value="<?php echo $rating_type[$i] ?>" />
      <?php echo $rating_type[$i] ?>
    </td>
  </tr>
<?php } ?>

Because this is a vanilla JavaScript solution which uses querySelectorAll, dataset and Array.prototype.forEach this may be not running on all browsers you want.

Sign up to request clarification or add additional context in comments.

4 Comments

this works for me, but OP tagged jQuery so why not just do the safe and browser agnostic thing and use it?
@nothingisnecessary because i wanted to provide a different (vanilla JS) solution.
@Werner if you see my code i use loop to print my check boxes. Its not working for me
@Werner Thank You So much. you made my life
1

$('.allcb').on('click', function() {
  $(this).parent().siblings().find('.chk').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="checkbox" name="opinion[]" class="allcb" data-child="chk" value="<?php echo $opinion[$i]?>" />
      <?php echo $opinion[$i]?>
    </td>
    <td>
      <input type="checkbox" name="action[]" class="chk" value="<?php echo $action[$i] ?>" />
      <?php echo $action[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="long_term[]" class="chk" value="<?php echo $long_term[$i] ?>" />
      <?php echo $long_term[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="p_long_term[]" class="chk" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
      <?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
    </td>
    <td>
      <input type="checkbox" name="short_term[]" class="chk" value="<?php echo $short_term[$i] ?>" />
      <?php echo $short_term[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="p_short_term[]" class="chk" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
      <?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
    </td>
    <td>
      <input type="checkbox" name="outlook[]" class="chk" value="<?php echo $outlook[$i] ?>" />
      <?php echo $outlook[$i] ?>
    </td>
    <td>
      <input type="checkbox" name="rating_type[]" class="chk" value="<?php echo $rating_type[$i] ?>" />
      <?php echo $rating_type[$i] ?>
    </td>
  </tr>
</table>

1 Comment

Updated with table and tr tags and jQuery selector also.
1

You can do it by adding a kind of reference on the other check boxes to the main check box you are checking. Then, when clicking on the main check box, you can control the others. Like this:

Javascript:

    $('.allcb').on('click', function(){
        var index = $(this).data('index');

        if ($(this).is(':checked'))
        {
            $('.childChk' + index).prop('checked', true);
        }
        else
        {
            $('.childChk' + index).prop('checked', false);
        }
    });

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <?php
            for ($i=0; $i<count($opinion); $i++) {
        //if ($opinion[$i] == "")continue;
            ?>
              <tr>
                <td>
                 <!-- <input type="text" name="opinion[]" value="<?php //echo $opinion[$i]?>" size="28" readonly="readonly" />-->

          <input type="checkbox" name="opinion[]" class="allcb" data-child="chk" data-index="<?=$i?>" value="<?php echo $opinion[$i]?>" />
          <?php echo $opinion[$i]?>
        </td>
        <td>
          <input type="checkbox" name="action[]" class="chk chkChild<?=$i?>" value="<?php echo $action[$i] ?>" />
          <?php echo $action[$i] ?>
        </td>
        <td>
          <input type="checkbox" name="long_term[]" class="chk chkChild<?=$i?>" value="<?php echo $long_term[$i] ?>" />
          <?php echo $long_term[$i] ?>
        </td>
        <td>
          <input type="checkbox" name="p_long_term[]" class="chk chkChild<?=$i?>" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
          <?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
        </td>
        <td>
          <input type="checkbox" name="short_term[]" class="chk chkChild<?=$i?>" value="<?php echo $short_term[$i] ?>" />
          <?php echo $short_term[$i] ?>
        </td>
        <td>
          <input type="checkbox" name="p_short_term[]" class="chk chkChild<?=$i?>" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
          <?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
        </td>
        <td>
          <input type="checkbox" name="outlook[]" class="chk chkChild<?=$i?>" value="<?php echo $outlook[$i] ?>" />
          <?php echo $outlook[$i] ?>
        </td>
        <td>
          <input type="checkbox" name="rating_type[]" class="chk chkChild<?=$i?>" value="<?php echo $rating_type[$i] ?>" />
          <?php echo $rating_type[$i] ?>
        </td>
      </tr>
    <?php
            }
    ?>

Note that I added the $i counter to your child check boxes class. This won't change the behavior of any DOM element.

EDIT:

You may NOT call the jQuery library inside the loop. The jQuery library MUST be called just one time. If you call several times, all the solutions presented here will not work.

4 Comments

Did you removed the $(document).ready statement? I put here only for reference, you should not use in your code. Just take the function implementation and the changes in the HTML code. I edited to remove the document.ready.
I Copy your code and paste as it is after removing $(document).ready but it still not working
I've edited now the HTML part. Try to copy it and check if it works now. You must call the jQuery library just one time in your code, or nothing will work.
What if you print the index var? Tell me what you get when doing alert(index) inside javascript code, please. Let's debug it.
1
Simple use this : 

$(document).ready(function(){
  $('.allcb').on('click', function(){
    $(this).parent("td").parent("tr").find('.chk').prop('checked', this.checked);

  });
});

2 Comments

I have edited the code , refer that, you were missing document ready so the checkbox click event is not bind and also too many parent are useless.
Its Not Working Yet (
1

You can try this,

 $('.allcb').on('click', function(){  
      $(this).closest('tr').find('.chk').prop('checked', this.checked);  
 }); 

Or

 $('.allcb').on('click', function(){  
      $(this).parents('tr').find('.chk').prop('checked', this.checked);  
 }); 

this is just Pekka answer with 1 line more.

1 Comment

+1 Sunny must be doing it wrong, because this works for me and I use a solution like this all the time in enterprise web apps. (or did, until I started using AngularJS)
0

If you want to check all the checkBoxes using javascript,

You can give all the checkbox a class,

and then

var a = document.getElementsByClassName("yourClassName"); for(var key in a) { a[key].checked = true; }

or

if you want to use jQuery ,

$(".yourClassName").attr("checked",true);

Comments

0

This solution plays nice with dynamic elements, and uses className to identity the row (.option-row) instead of relying on tagName so that you're not committed to using specific elements to display the data.

Make sure that you include a reference to jquery.js before you call the $ function (as in the example below).

// check or uncheck all boxes with class 'chk' when 'allcb' is clicked
$(document).on('click', '.allcb', function() {
  $('.chk',$(this).closest('.option-row')).prop('checked', this.checked);
});

// simulate PHP; render some rows for demo
var html = [];
for (var i = 0; i < 5; i++) {
  html.push('<tr class="option-row"><td><input type="checkbox" class="allcb cb"/></td><td><input type="checkbox" class="chk"/></td><td><input type="checkbox" class="chk"/></td></tr>');
}
$("tbody").html(html.join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Opinion</th>
      <th>Column A</th>
      <th>Column B</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

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.