Boltz0r Boltz0r - 6 months ago 15
HTML Question

Uncaught SyntaxError: Unexpected token ILLEGAL on Toggle

I am getting this error when i try to use the toggle function. It might be because of <%=i%> but im not sure

<% @categorias.each do |categoria| %>
<%i += 1%>
<div id = "Categoria" onclick = "$(#<%=i%>).toggle();">
<b> <%= categoria.categoria_pt %></b>
</div>
<% @pratos_precos.each do |pratos_preco| %>

<% if @pratos.find(pratos_preco.prato_id).categoria_pratos_id.to_s == categoria.id.to_s %>
<div id = <%=i%> style = "display:none">
<tr>
<table class="table-condensed table-bordered" style= "width: 98%">
<td><%= @pratos.find(pratos_preco.prato_id).nome_pt %></td>
</div>


I get that error when i click on the Category div... why?

EDIT:

If i do it like this :

<div id = "Categoria" onclick = "$( "#<%=i%>" ).toggle();">


i get this error :

Uncaught SyntaxError: Unexpected token }

Answer

Try this code:

<% @categorias.each do |categoria| %>
  <% i += 1 %>
  <div id = "Categoria" onclick = "$('#<%= i %>').toggle();">
    <b><%= categoria.categoria_pt %></b>
  </div>
  <% @pratos_precos.each do |pratos_preco| %>
    <% if @pratos.find(pratos_preco.prato_id).categoria_pratos_id.to_s == categoria.id.to_s %>
      <div id = "<%= i %>" style = "display:none">
        <tr>
        <table class="table-condensed table-bordered" style= "width: 98%">
          <td><%= @pratos.find(pratos_preco.prato_id).nome_pt %></td>
      </div>

You'll notice that the #<%= i %> section is now surrounded in single quotes to make the resulting jQuery selector valid. Single quotes are used instead of double quotes, as double quotes are already surrounding the onclick handler, which includes the jQuery selector.

Also, the line with <div id = "<%= i %>" style = "display:none"> now uses double quotes around the id value, as per HTML specs.

With those two changes, it looks like this should work as expected.

Comments