Function to concatenate html and jquery table data

3

I have a table in html with a checkbox in each row what I need is that when selecting the checkbox I take the value of a cell

<table>
    <thead>
        <th>Seleccionar</th>
        <th>ejemplo</th>
        <th>ehemplo</th>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" onclick="guardadatos();"></td>
            <td>ejemplo</td>
            <td>ejemplo</td>
        </tr>
        <tr>
            <td><input type="checkbox" onclick="guardadatos();"></td>
            <td>ejemplo</td>
            <td>ejemplo</td>
        </tr>
    </tbody>
</table>

and the next function if I take the value of the cell but when selecting the other checkbox, I concatenate them and repeat the value, showing me an "undefined" each time the each is repeated

function guardadatos() {
    $("input[type=checkbox]:checked").each(function(){
        id = $(this).parents("tr").find("td").eq(1).html();
        texto += id;
        texto +="<br/>";
      });
}
    
asked by arglez35 09.08.2018 в 20:37
source

1 answer

1

You have to initialize the text variable within the function. Something like this:

function guardadatos() {
    var texto = '';
    $("input[type=checkbox]:checked").each(function(){
        id = $(this).parents("tr").find("td").eq(1).html();
        texto += id;
        texto +="<br/>";        
      });
      console.log(texto);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <thead>
        <th>Seleccionar</th>
        <th>ejemplo</th>
        <th>ehemplo</th>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" onclick="guardadatos();"></td>
            <td>ejemplo</td>
            <td>ejemplo</td>
        </tr>
        <tr>
            <td><input type="checkbox" onclick="guardadatos();"></td>
            <td>ejemplo</td>
            <td>ejemplo</td>
        </tr>
    </tbody>
</table>
    
answered by 09.08.2018 / 20:52
source