Ad

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.

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';
    };
});
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad