0

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.

agenda.php:

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

app.js:

// Hide/Show button of del
$("#taskSelect").click(function () {
    if( $("#taskSelect").is(':checked') ) {
        $("#writeTask").hide();
        document.getElementById("deleteTask").style.display = 'block';
    } else {
        $("#writeTask").show();
        document.getElementById("deleteTask").style.display = 'none';
    };
});
  • 1
    `id` fields are meant to be unique, use a class if you want to handle multiple elements. (See: [Link](http://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page)) – ccKep Jan 14 '16 at 00:46

1 Answers1

1

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.

ajshort
  • 3,684
  • 5
  • 29
  • 43