Coffeescript on Rails - select items from a table

Asked

Viewed 75 times

1

Hello! I have the following code generated by Scaffold:

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

<h1>Produtos</h1>

<table class="table table-striped" id="tabelaProdutos">
  <thead>
    <tr>
      <th>Nome</th>
      <th>Preco</th>
      <th>Descricao</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @produtos.each do |produto| %>
      <tr>
        <td><%= produto.nome %></td>
        <td><%= produto.preco %></td>
        <td><%= 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="select()" />

<br>

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

I need to make that the items in this table are selected and that through a button, I can add the Float values (column "Price") of these selected items. The point is that I’m bad at javascript and I don’t know Coffeescript. I don’t know where to start and I couldn’t find a tutorial on Coffeescript. This need is part of a college job.

1 answer

0

Ok, so let’s create the possibility of selecting table items by changing the line of HTML code as follows:

<td><input type="checkbox"value=<%= produto.preco %>><%= produto.preco %></td>

And after </table>:

<div id="total">

</div>

And on your.coffee product goes the code:

$(document).ready ->
  somaSelecionados = ->
    n = $('input:checked').length
    sum = 0
    $('input:checked').each ->
      sum += parseFloat($(this).val())
      return
    $('#total').text n + (if n == 1 then ' is' else ' are') + ' checked:' + sum
    return

  somaSelecionados()
  
  $('#soma').on 'click', somaSelecionados

  • The sum is not made with all table elements. Only with what I select with the mouse.

  • See if you can test the new solution, I think it will all work now.

Browser other questions tagged

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