Null return of a JS object in Rails

Asked

Viewed 24 times

0

I have the following code:

<p id="notice"><%= notice %></p>

<h1>Produtos</h1>

<table class="table table-hover custom" id="tabelaProduto">
  <thead>
    <tr>
      <th>id</th>
      <th>Nome</th>
      <th>Preco</th>
      <th>Descricao</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @produtos.each do |produto| %>
      <tr>
        <td><%= produto.id %></td>
        <td><%= produto.nome %></td>
        <td><%= produto.preco %></td>
        <td data-jtable><%= produto.descricao %></td>
        <td><%= link_to 'Show', produto %></td>
        <td><%= link_to 'Edit', edit_produto_path(produto) %></td>
        <td><%= link_to 'Destroy', produto, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>
<input type="button" id="botaosomar" value="OK" onclick="vamosSomar()" />

<br>

<%= link_to 'New Produto', new_produto_path %>

and the javascript of this view contained in app/Assets/Javascripts:

var tabela = document.getElementById("tabelaProduto"); console.log(tabela.firstElementChild);

I don’t know why rays are returning null on this object :\

1 answer

0

I discovered the reason... was what I suspected: JS was being loaded before the HTML rendering, hence the ID of the table I was using as a parameter to assign it to a variable, did not "exist" at the time of that assignment.

I reformatted the code as follows:

$(document).ready(function(){
    var tabela = document.getElementById("tabelaProduto");
    console.log(tabela.firstElementChild);
});

it worked ! Thanks for everyone’s attention. One’s doubt can be another’s doubt.

Browser other questions tagged

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