How to read values from an html table with js

Asked

Viewed 798 times

0

I have a table tbLista html with some values filled and wanted to read it by JS, my Js code is of the second way:

    var rowIndex = -1;
var beneficiarios = [];

$(document).ready(function () {
    $('#formCadastro').submit(function (e) {
        e.preventDefault();
        var lista = document.getElementById('tbLista').rows;    
        for (var i = 1; i < lista.length; i++) {
            beneficiarios.push(JSON.stringify({ "cpf": lista[i].cells[0].innerHTML, "nome": lista[i].cells[1].innerHTML }));
        }
        $.ajax({
            url: urlPost,
            method: "POST",
            data: {
                "NOME": $(this).find("#Nome").val(),
                "CEP": $(this).find("#CEP").val(),
                "Email": $(this).find("#Email").val(),
                "Sobrenome": $(this).find("#Sobrenome").val(),
                "Nacionalidade": $(this).find("#Nacionalidade").val(),
                "Estado": $(this).find("#Estado").val(),
                "Cidade": $(this).find("#Cidade").val(),
                "Logradouro": $(this).find("#Logradouro").val(),
                "Telefone": $(this).find("#Telefone").val(),
                "Cpf": $(this).find("#Cpf").val(),
                "Beneficiarios": JSON.stringify(beneficiarios)
            },
            error:
                function (r) {
                    if (r.status == 400)
                        ModalDialog("Ocorreu um erro", r.responseJSON);
                    else if (r.status == 500)
                        ModalDialog("Ocorreu um erro", "Ocorreu um erro interno no servidor.");
                },
            success:
                function (r) {
                    ModalDialog("Sucesso!", r)
                    $("#formCadastro")[0].reset();
                }
        });
    });
});

Html:

    <div class="row">
        <div class="col-lg-5">
            <div class="form-group">
                <label for="CpfBeneficiario">CPF:</label>
                <input type="text" class="form-control" id="CpfBeneficiario" name="CpfBeneficiario" placeholder="Ex.: 010.011.111-00" maxlength="14">
            </div>
        </div>
        <div class="col-lg-5">
            <div class="form-group">
                <label for="NomeBeneficiario">Nome:</label>
                <input type="text" class="form-control" id="NomeBeneficiario" name="NomeBeneficiario" placeholder="Ex.: João" maxlength="50">
            </div>
        </div>
        <div class="col-lg-2">
            <div class="pull-right">
                <button id="btnIncluir" type="button" onclick="AddBeneficiarios();" class="btn btn-sm btn-success" style="margin-top: 45%">Incluir</button>
            </div>
        </div>
    </div>

<table id="tbLista" class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayName("CPF")
            </th>
            <th>
                @Html.DisplayName("Nome")
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>        
    <tbody>
</table>

How to do?

  • 1

    without displaying html will not help

  • post all your code so we can help you better, hug

  • @Ricardopunctual Posted the HTML

1 answer

0

Your code is using jQuery, so you don’t have to mix up some stuff like that line:
var lista = document.getElementById('tbLista').rows;, that may simply be so:
var lista = $('#tbLista').rows;.

As for reading the lines, each td within Row can be read with an index, for example $(tr).find('td:eq(0)') is the first, and so on. I suggest you use something more acerctive, like a class, for example $(tr).find('.td-cpf'), but I don’t know how it generated the table, so I’ll leave it to the positional one, which works like this:

var beneficiarios = [];

var lista = $('#tbLista tbody');  

$(lista).find("tr").each(function(index, tr) {
   
   beneficiarios.push(JSON.stringify({ "cpf": $(tr).find('td:eq(0)').html(), "nome": $(tr).find('td:eq(1)').html() }))
});

console.log(beneficiarios);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="tbLista" class="table">
    <thead>
        <tr>
            <th>
                CPF
            </th>
            <th>
                Nome
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody> 
		<tr>
			<td>1</td>
			<td>João</td>
		</tr>
		<tr>
			<td>2</td>
			<td>Maria</td>
		</tr>
    <tbody>
</table>

See that to get the contents of td used .html()

Browser other questions tagged

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