Jhauge Jhauge - 1 year ago 105
Javascript Question

Only the first checkbox value is being added to my table

Regardless of how many items I check in my list of checkboxes, when I review the table I am adding a row to, only the value of the first checkbox that is checked is added to my table. I am trying to go through each and grab the value of each checkbox to insert but it does not seem to be working. any clue where i am screwing up?

In my jquery, I am running an if statement to prevent the addition of undefined to my table when a box is unchecked.

Here is a jsfiddle demonstrating whatI am doing: http://jsfiddle.net/22L9x006/

$(document).on('click', 'input:checkbox[name=certsToValid]', function() {
$newTableRow = '<tr><td><p>' + $('[name=certsToValid]:checked').val() + '</p></td><td><input type="text" placeholder="Credential #..." class="certInput" /></td><td><p>$5.00</p></td><td><div class="removeRow"></div></td></tr>';
if($.each($('input:checkbox[name=certsToValid]').is(':checked')) && $(this) != undefined) {

Answer Source

Here is an extension to PeterKA's answer. The code is identical to his. I only added a kind of "filtering" to avoid duplicate rows.

 $(document).on('change', ':checkbox[name=certsToValid]', function () {
        $(this).filter(':checked').each(function () {
            $newTableRow = '<tr><td><p>' + this.value + '</p></td><td><input type="text" placeholder="Credential #..." class="certInput" /></td><td><p>$5.00</p></td><td><div class="removeRow">REMOVE</div></td></tr>';

            var optionValue = this.value;

            var added = false;

            $('.certSelections td:first-child p').each(function (index) {

                if ($(this).text() === optionValue) {
                    added = true;

            //only add if it's not found in the table  
            if (!added) {

                $('.certSelections tbody').append($newTableRow);



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download