Scroll through a table and take data with javascript

Asked

Viewed 3,605 times

1

I’m new with Javascript and I need to go through the lines of a table and if the checkbox is marked, take the value of a column(ID) and store in a array.

  • Give an example of how your table looks.

  • ID? You want to take the value of another TD on the same line as the checkbox that’s it?

  • Ideal is to show how the html code of the page is

1 answer

0


You did not inform the table structure, but no matter the structure, the code below will catch the id of the column you indicate in the variable:

var coluna = 3; // coluna em que está o ID

The code goes through each row of the table and checks for a checkbox marked; if there is, it will catch the id of td (column) reported in the variable above (var coluna) and insert into the array var ids = [];.

See example:

$(document).ready(function(){
   
   var ids = [];
   var coluna = 2; // coluna em que está o ID
   
   $("table tr").each(function(){
      
      if($(this).find("input[type='checkbox']").is(":checked")){
         
         ids.push($(this).find("td:eq("+(coluna-1)+")").attr("id"));
      }
      
   });
   console.log(ids);
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
   <th>
      Coluna 1
   </th>
   <th>
      Coluna 2
   </th>
   <th>
      Coluna 3
   </th>
   <tr>
      <td id="linha1">
         <input type="checkbox" />
      </td>
      <td id="linha1_1">
         col 2, linha 1
      </td>
      <td id="linha1_2">
         col 3, linha 1
      </td>
   </tr>
   <tr>
      <td id="linha2">
         <input type="checkbox" checked />
      </td>
      <td id="linha2_1">
         col 2, linha 2
      </td>
      <td id="linha2_2">
         col 3, linha 2
      </td>
   </tr>
   <tr>
      <td id="linha3">
         <input type="checkbox" checked />
      </td>
      <td id="linha3_1">
         col 2, linha 3
      </td>
      <td id="linha3_2">
         col 3, linha 3
      </td>
   </tr>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.