简体   繁体   中英

checkbox toggle select all/unselect all problem

hi i found a script which uses checkbox to select all/ unselect all checkboxex which i found a working example here http://jsfiddle.net/ThiefMaster/HuM4Q/

the problem is when i tried to integrate it to my own html. it doenst work anymore, here is my code:

javascript:

<head>
<script>
$('#checkAll').click(function() {
    if(this.checked) {
        $('input:checkbox').attr('checked', true);
    }
    else {
        $('input:checkbox').removeAttr('checked');
    }
});

$('input:checkbox:not(#checkAll)').click(function() {
    if(!this.checked) {
        $('#checkAll').removeAttr('checked');
    }
    else {
        var numChecked = $('input:checkbox:checked:not(#checkAll)').length;
        var numTotal = $('input:checkbox:not(#checkAll)').length;
        if(numTotal == numChecked) {
            $('#checkAll').attr('checked', true);
        }
    }
});
</script>
</head>

and these is my html:

<h2>Courses</h2>
<?php 
$attributes = array('name' => 'list','id' => 'form' );
echo form_open('courses/edit',$attributes);?>

<table class="data display datatable" id="example">
    <thead>
        <tr>
          <th>ID</th>
          <th>Title</th>
          <th>Description</th>
          <th>Units</th>
          <th>Notes</th>
          <th><input type="checkbox" id="checkAll"></th>
        </tr>
    </thead>
    <tbody> 
<?php foreach($query->result_array() as $row): ?>
        <tr class="even gradeC">
            <td><?php echo anchor('courses/details/'.$row['courseID'],$row['courseID']);?></td>
            <td><?php echo $row['courseTitle'];?></td>
            <td><?php echo $row['courseDesc'];?></td>
            <td><?php echo $row['courseUnits'];?></td>
            <td><?php echo $row['courseNotes'];?></td>
            <td><input type="checkbox" name="checkID[]" id="checkID" value="<?php echo $row['courseID'];?>"/></td>
        </tr>
<? endforeach; ?>
    </tbody>
</table>

Try fixing this line:

<td><input type="checkbox" name="checkID[]" id="checkID" value="<?php echo $row['courseID'];?>"/></td>

The id attribute should be unique, eg, only one element should have the id "checkID", not every row. Try removing the attribute altogether or make it unique for each row to see if your javascript sorts itself out.

Also, you need a line like this at the top, in your head:

  <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script> 

That script used jQuery. Make sure you include the jQuery script in your page.

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