Event In JS Only Works On First Checklist Inside Of A Foreach

- 1 answer

I have a function that monitors a list of checkboxes to detect if some are selected. If some are selected the button shows, otherwise the button hides. The checkbox lies within of a foreach in PHP to transform into a list of checkboxes.

The problem is that only the first checkbox shows the delete button.


    <form id="delTask" name="delTask" method="POST" action="">
        <?php foreach ($tasks as $value): ?>
                    <div class="checkbox">
                            <input name="excluir[]" value="<?php echo $value[0] ?>" id="taskSelect" type="checkbox">
                <td><?php echo $value[1] ?></td>
                <td><span class="label label-success">+50</span></td>
        <?php endforeach; ?>


// Hide/Show button of del
$("#taskSelect").click(function () {
    if( $("#taskSelect").is(':checked') ) {
        document.getElementById("deleteTask").style.display = 'block';
    } else {
        document.getElementById("deleteTask").style.display = 'none';


The problem is that you have many checkbox inputs with the ID taskSelect. Element IDs must be unique throughout the whole document. Instead you will want to use a class name, as the same class can be attached to multiple elements:

<input name="excluir[]" value="<?php echo $value[0] ?>" class="taskSelect" type="checkbox">

You then use a selector like .classname rather than #id in your jQuery click handler:

$(".taskSelect").click(function () {

As an aside, rather than doing document.getElementById("id").style.display to show and hide things, as your are using jQuery you can just use $("#id").show() and $("#id").hide() throughout.