0

I have a table whose cells may contain textboxes, radio buttons, checkboxes I have given each a class - so all textboxes are class "T", checkboxes are class "C" and so on

I want to iterate over all the rows and get the value of each input. I have tried this

function gather() {
    var res = '';
    var table = document.getElementById("tblQ");
    for (var i = 0, row; row = table.rows[i]; i++) {
        if (row.style.display !== 'none') {
            $('.T').each(function () {
                if ($.trim($(this).val()) !== '') 
                    res += $(this).attr('id') + '~' + $(this).val() + '\n';
            });
            $('.C').each(function () {
                if ($(this).is(':checked')) 
                    res += $(this).attr('id') + '~1\n';
            });
            $('.R').each(function () {
                if ($(this).is(':checked')) 
                    res += $(this).attr('id') + '~1\n';
            });
        }
    }
    alert(res);
}
<table id="tblQ">
  <tr>
    <td>
      <input id="01" type="text" value="myText" class='T' />
    </td>
  </tr>
  <tr>
    <td>
      <input id='02' type="checkbox" checked class='C' />
    </td>
  </tr>
</table>
<p />
<button onClick='gather()'>Test</button>

This gives

01~myTest
02~1
01~myTest
02~1

How do I restrict the ".each" to the class within the current row.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Phil
  • 1
  • 1
    Why are you mixing vanilla JS with jquery? – DarkBee Jan 24 '23 at 14:25
  • Does this answer your question? [jQuery - selecting elements from inside a element](https://stackoverflow.com/questions/5808606/jquery-selecting-elements-from-inside-a-element) – DarkBee Jan 24 '23 at 14:26
  • Why do you use `".C"` when you can go for `'[type="checkbox"]'`? _ also what should be that `$('.R')` ? – Roko C. Buljan Jan 24 '23 at 14:28
  • Just out of curiosity, what are you building? What's the meaning of `~1`? – Roko C. Buljan Jan 24 '23 at 14:29
  • `$('.T').each(` -> `$('.T', row).each(` (same for .C/.R) *or* (equivalent) `$(row).find(".T").each(` – freedomn-m Jan 24 '23 at 15:45
  • Thanks everyone. I solved it with a combination of DarkBee's and Freedomn-m's suggestions. My selector is now $('#tblQ > tbody > tr').each(function() { if ($(this).css('display') !== 'none') { $('.T', this).each(function () { and so on – Phil Jan 26 '23 at 09:05

0 Answers0