CoffeeScript on Rails - select items from a table

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 have the items in this table selected and that with a button, I can add the Float values ("Price" column) of these selected items. The issue is that I am lousy in javascript and I do not know CoffeeScript. I do not know where to start and I did not find a didactic tutorial on CoffeeScript. This need is part of a college job.

    
asked by anonymous 26.05.2017 / 16:26

1 answer

0

Ok, so let's create the possibility of selecting the 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 in your product.coffee 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
    
29.05.2017 / 15:22