ndemoreau
ndemoreau

Reputation: 3869

each loop in coffeescript, jquery

I'm new to javascript and starting the mix javascript + jquery + coffeescript all together is not easy for a newbie like me...

I've created a very simple sortable list and I'd like to renumber my list on the fly (the server side code is ok).

The coffeescript code I wrote is:

jQuery ->
  $('.simple_grid tbody').sortable
    axis: 'y'
    containment: 'parent'
    cursor: 'move'
    tolerance: 'pointer'
    update: (event,ui)->
      $.post($(this).attr('dataupdateurl') + '/' + ui.item.attr('id') + '/reorder/' + ui.item.index())
      $('tr > td > a > span.number').each (i, element)  =>
      $(element).html i

This generates a table of this kind

<table class= "simple-grid">
   <tbody dataupdateurl = "xxx">
      <tr>
         <td>
            <a href="some_link"><span class="number">1</span>text 1</a>
         </td>
          <td>
            <a href="some_link"><span class="number">2</span>text 2</a>
         </td>
        <td>
            <a href="some_link"><span class="number">3</span>text 3</a>
         </td>
      </tr>
   </tbody>
</table>

I'm trying to renumber what's inside the span.number elements when the update callback triggers but I get following error message:

element is not defined

Any help would be very welcome! Thanks!

UPDATE: the problem was due to the fact that I missed an indent in the last function:

$('span.number').each (i, element)  =>
      $(element).html i

Upvotes: 4

Views: 7812

Answers (1)

Kosmosniks
Kosmosniks

Reputation: 186

I don't know coffee script but generally using jQuery selector doesn't require the full path. e.g. $('tr > td > a > span.number') could be rewritten as $('.number'), also the .each() is generally used as .each(function(index, element) { YOUR CODE });. The last thing that looks out of place is setting the html this is generally done as .html('value'). So in your case $(element).html(i);. Hope this helps?

Upvotes: 4

Related Questions