Bruce
Bruce

Reputation: 1071

How do I attach checkboxes to a submit

I have unknown amount of checkbox inputs on a page created based on rows in an sql database.

The checkboxes look like:

<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">

The checkboxes are intended, when checked and submitted, to delete a row from the database based on the value of $mid

The checkboxes could be either loose (not contained in any forms), or each could be contained in its own form (without a submit button). There is no way however to contain all the checkboxes in one form.

The reason is it's displayed in a loop with output like this:

<tr>
<td><input type="checkbox" class="deletefunc" value="<? echo $mid; ?>"></td>
<td><input type="checkbox" class="star" value="1"> <!-- jquery/ajax onclick function --></td>
<td><a href></td>
<td><form name....><input type="submit" value="something"></form></td>
<tr>

So what I need help understanding is, how to gather all the checkboxes based on classname, and attach them to a submit button....

And further, how would I write the loop function so it knows how many deletes to perform? What I mean is, how would I write a loop that would get the values from an unknown amount of inputs. Normally I know how many inputs there are and what the names are so its a matter of assigning a variable for each input.... I've never done this with an unknown amount of inputs.

Upvotes: 0

Views: 53

Answers (1)

dave
dave

Reputation: 64695

I would do it like this:

HTML:

<input type="checkbox" class="deletefunc" value="<? echo $mid; ?>">
<button id="delete-them">Delete Them</button>

JS:

$(function() {
    $('#delete-them').on('click', function() {
        var data = $('.deletefunc').attr('name', 'delete[]').serialize();
        $.ajax('delete-them.php', { 
            method: 'POST',
            data: data, 
            success: function() {
                alert('deleted!');
            }
         });
     });
});

PHP:

<?php
    $ids = $_POST['delete'];
    $params = array_fill(0, count($ids), "?");
    $sql = "DELETE FROM some_table WHERE id IN (" . implode(",", $params) . ")";
    //DELETE FROM some_table WHERE id IN(?,?,?,?);
    $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
    $stmt = $pdo->prepare($sql);
    $stmt->execute($ids);
?>

So we basically listen for a click on our button, when it happens, we set the name (with [] at the end so it becomes an array) for all of the items with the class we care about, so that when we serialize those items we know how to reference it in our PHP.

We then POST that data over to the server, where we read the array we just sent, see how many there are, and then create a query to delete those items.

Upvotes: 1

Related Questions