Mysql
 sql >> Database >  >> RDS >> Mysql

Avvolgi alcuni input con la sua casella di controllo e invia al database

Non è così difficile, per questo HTML:

<table>
    <thead>
        <tr>
            <th>Mark</th>
            <th>Name</th>
            <th>Qty</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" name="id[1]" /></td>
            <td><input type="text" name="name[1]" /></td>
            <td><input type="text" name="quantity[1]" size="3" /></td>
            <td><input type="text" name="price[1]" size="3" /></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="id[2]" /></td>
            <td><input type="text" name="name[2]" /></td>
            <td><input type="text" name="quantity[2]" size="3" /></td>
            <td><input type="text" name="price[2]" size="3" /></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="id[3]" /></td>
            <td><input type="text" name="name[3]" /></td>
            <td><input type="text" name="quantity[3]" size="3" /></td>
            <td><input type="text" name="price[3]" size="3" /></td>
        </tr>
        <tr>
            <td colspan="4"><input id="save" type="button" value="Submit" /></td>
        </tr>
    </tbody>
</table>
<h3>Post data:</h3>
<div class="submit_data">click Submit...</div>

Lo snippet jQuery completo sarebbe:

$('input[name^=id]').on('change', function(e) {
    var thisCheckbox = $(this);
    var thisRow = thisCheckbox.closest('tr');
    if ( thisCheckbox.is(':checked') ) {
        thisRow.addClass('row_selected');
    } else {
        thisRow.removeClass('row_selected');
    };
});
$('#save').on('click', function(e) {
    e.preventDefault();
    var toPost = $('.row_selected input').serialize();
    /* Now post and insert into database */
    $.post('insert_into_db.php', toPost, function(data) {
        alert('Success!');
    });
});

Guarda il codice in azione .

In PHP le variabili pubblicate sono array come:

[id] => Array
    (
        [1] => on
        [3] => on
    )

[name] => Array
    (
        [1] => My name 1
        [3] => My name 3
    )

[quantity] => Array
    (
        [1] => 100
        [3] => 50
    )

[price] => Array
    (
        [1] => 23.34
        [3] => 15.23
    )

e puoi sfogliarli in questo modo:

foreach( $_POST['id'] as $id=>$on ) {
    echo 'ID: ' . $id . '<br />';
    echo 'Name: ' . $_POST['name'][$id] . '<br />';
    echo 'Qty: ' . $_POST['quantity'][$id] . '<br />';
    echo 'Price: ' . $_POST['price'][$id] . '<br />';
    echo '<hr />';
};

che emette:

ID: 1
Name: My name 1
Qty: 100
Price: 23.34
------------------
ID: 3
Name: My name 3
Qty: 50
Price: 15.23
------------------

Nota:su alcuni dispositivi dovrai disattivare la cache jQuery, in generale:

$.ajaxSetup({ cache: false });

o post specifico:

$.ajaxSetup({
   type: 'POST',
   headers: { "cache-control": "no-cache" }
});