vendredi 23 mars 2018

Jquery selector for checkboxes not getting correct items

I have a page that contains x number of rows, dynamically generated from a database. Each form has a set of checkboxes and a save button. Everything else is working correctly, but it seems like no matter which save button I click, it's pulling in the selections from all the forms (after the first one; whichever save button I click first has the correct selections.) Where am I going wrong here?

<table>
    <tr class="even">
        <td class="checksCol">
            <input type="checkbox" name="pages_new" id="new_10" value="10">salads<br>
            <input type="checkbox" name="pages_new" id="new_9" value="9">sandwiches<br>
            <input type="checkbox" name="pages_new" id="new_7" value="7">sides<br>
            <input type="checkbox" name="pages_new" id="new_14" value="14">soups<br>
        </td>
    </tr>
    <tr class="odd">
        <td colspan="3">
            <input type="button" class="saveDisclaimer" id="saveDisclaimer_new" value="Save">
        </td>
    </tr>
</table>

<table>
    <tr class="even">
        <td class="checksCol">
            <input type="checkbox" name="pages_2" id="2_10" value="10">salads<br>
            <input type="checkbox" name="pages_2" id="2_9" value="9">sandwiches<br>
            <input type="checkbox" name="pages_2" id="2_7" value="7">sides<br>
            <input type="checkbox" name="pages_2" id="2_14" value="14">soups<br>
        </td>
    </tr>
    <tr class="odd">
        <td colspan="3">
            <input type="button" class="saveDisclaimer" id="saveDisclaimer_2" value="Save">
        </td>
    </tr>
</table>

$(document).ready(function() {
  $('.saveDisclaimer').click( function(e) {
    var id = this.id.split("_").pop();
    console.log("id: " + id);
    var pages = [];

    $('input[name="pages_"+id]:checked').each(function() {
      pages.push(this.value);
    });
    console.log("pages from input name=pages_" + id);
    console.log(pages);

    e.preventDefault();
  });

});

JSBin example - select a few checkboxes from the first form; click save. The console shows the correct selections. Then, without deselecting the checkboxes, click a few in the second form, and click the second save button. The console shows ALL checkboxes that are still selected, not just the ones that go with the particular save button.




Aucun commentaire:

Enregistrer un commentaire