mardi 1 décembre 2015

Rails 4: conditional if statement with coffeescript not working

In my Rails app, I have a Post model.

I am using coffeescript to make the post form more dynamic.

In posts.coffee, I have:

$(document).ready ->
  text_max = 140
  $('#character_count').html text_max + ' characters remaining'
  $('#post_short_copy').keyup ->
    text_length = $('#post_short_copy').val().length
    text_remaining = text_max - text_length
    $('#character_count').html text_remaining + ' characters remaining'
    return
  return

This works really well.

Now, I need to insert an if statement inside this code, to only execute $('#character_count').html text_max + ' characters remaining' if $('#post_short_copy').is(':empty').

I have tried the following code:

$(document).ready ->
  text_max = 140
  if $('#post_short_copy').is(':empty') {
    $('#character_count').html text_max + ' characters remaining'
  }
  $('#post_short_copy').keyup ->
    text_length = $('#post_short_copy').val().length
    text_remaining = text_max - text_length
    $('#character_count').html text_remaining + ' characters remaining'
    return
  return

but this returns an error:

SyntaxError: [stdin]:7:3: unexpected if

Any idea how to properly implement an if statement in coffeescript?

Aucun commentaire:

Enregistrer un commentaire