2014-11-02 35 views
1

無論我在複選框列表中選中多少個項目,當我查看錶格添加一行時,只檢查第一個複選框的值是添加到我的表中。我試圖通過每個並獲取每個複選框的值插入,但它似乎並沒有工作。任何線索,我搞砸了?只有第一個複選框值被添加到我的表中

在我的jQuery中,我正在運行一個if語句來防止在未選中框的情況下將未定義添加到我的表中。

這裏是一個展示的jsfiddle我whatI做: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>'; 
$(this).attr('value'); 
if($.each($('input:checkbox[name=certsToValid]').is(':checked')) && $(this) != undefined) { 
    $('.certSelections').append($newTableRow); 
} 
}); 
+0

花花公子提供一個名稱的複選框更簡單也創造了一個js小提琴 – 2014-11-02 18:46:53

+0

@ Anonymous.XI已經添加了的jsfiddle,謝謝 – Jhauge 2014-11-02 18:55:37

回答

0

這是PeterKA的答案的擴展。代碼與他的相同。我只添加了一種「過濾」來避免重複的行。

$(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); 
      } 
     }); 

    }); 

Fiddle

+0

謝謝@ jyrkim,這是完美的。我開始考慮添加這樣的過濾器來完成我的結帳過程的這一步。 – Jhauge 2014-11-02 19:56:24

1

我剛剛調整您的Fiddle所以用點擊複選框的值的選項被添加到表中。調整是改變

$newTableRow = '<tr><td><p>' + $('[name=certsToValid]:checked').val() + ... 

$newTableRow = '<tr><td><p>' + $(this).val() + ... 

這是不完整的解決方案,我想你如想要在取消選中複選框時刪除一行,當前每個複選框點擊都會添加一個新行,但我認爲您可以從這裏開始解決。

+0

謝謝你幫我指出了正確的方向,你幫我開始思考這個問題的正確方法 – Jhauge 2014-11-02 19:50:53

1

目前尚不清楚你的目標是什麼,但編寫代碼的正確方法是:

$(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>'; 
     $('p:contains(' + this.value + ')','.certSelections tbody').length || 
      $('.certSelections tbody').append($newTableRow); 
    }); 
}); 
$(document).on('click', 'div.removeRow', function() { 
    $(this).closest('tr').remove(); 
}); 

DEMO

如果你能澄清爲你想達到那麼這個答案會是什麼改進以更好地指導達到你的目標。

+0

謝謝你,我想我一直在想我想做什麼,對我來說這太讓人困惑了。我非常感謝幫助,因爲這正是我所期待的。 – Jhauge 2014-11-02 19:50:16

+0

@JordanHauge沒問題。很高興我能幫上忙。看到更新.. – PeterKA 2014-11-02 20:01:07

相關問題