简体   繁体   中英

Loop through a table and get the value of each checked checkbox

I have a problem right now. I'm trying to loop through my current table td and get each value of the checked checkboxes and concatenate all the checked values into a string, but I'm unable to accomplish it.

This is what I have so far:

HTML:

    <table class="TestTable">
      <tr>
         <td><input type="checkbox" id="chkBox1" value="TestVal1">Test Val 1</td>
         <td><input type="checkbox" id="chkBox2" value="TestVal2">Test val 2 </td>
       </tr>
       <tr>
          <td><input type="checkbox" id="chkBox3" value="TestVal3">Test val 3 
</td>
        </tr>
        </table>

Javascript:

var TableVals = "";
    $('.TestTable').each(function(){
        TableVals += $('.TestTable').find('input[type="checkbox"]:checked').val();
        alert(TableVals);
    })

So if id chkBox1, chkBox2, chkBox3 was checked, I'm expecting:

Test Val 1, Test val 2, Test val 3 are checked

If only chkBox1, then

 Test Val 1 is checked

JSFiddle attached here: https://jsfiddle.net/hegx4a0t/3/

You need to add an event listener to them so that the js will happen when the user clicks and not when the page loads where none of them will be checked.

https://jsfiddle.net/hegx4a0t/19

var tableVals = "";
var checkboxes = document.querySelectorAll('.TestTable input[type="checkbox"]')

checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function(e) {
    tableVals += e.target.value
    alert(tableVals)
  }, { once: true })
})

Please try this. It will work for you.

 var TableVals = "", helpingVerb = ' is '; var allCheckedInput = $('.TestTable td input[type="checkbox"]:checked'); for(key in allCheckedInput){ if(key > 0){ TableVals += ', '; } TableVals += $(allCheckedInput[key]).val(); } if(allCheckedInput.length > 1){ helpingVerb = ' are '; } var finalString = TableVals + helpingVerb + 'checked'; console.log(finalString); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="TestTable"> <tr> <td><input type="checkbox" id="chkBox1" value="Test Val 1" checked>Test Val 1</td> <td><input type="checkbox" id="chkBox2" value="Test val 2" checked>Test val 2 </td> </tr> <tr> <td><input type="checkbox" id="chkBox3" value="Test val 3">Test val 3</td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM