0

This is a fairly simple question but I can't seem to figure out why it's not working

I have this code:

$(".positive").numeric({ negative: false }, function() { alert("No negative values"); this.value = ""; this.focus(); })

which works when I put it in my view between <script> and </script>

However, when I copy and paste that formula to app->assets->javascripts-> page.js.coffee it doesn't work. I have even tried copy and pasting that code to JS2Coffee converter and pasting the coffee version of the code. Still no luck.

What am I doing wrong that my view does not recognize the javascript in my assets?

Here is the code in coffescript:

$(".positive").numeric
  negative: false
  , ->
  alert "No negative values"
  @value = ""
  @focus()

my application.js has

//= require jquery
//= require jquery_ujs
//= require jquery.numeric
//= require_tree .

1 Answer 1

1

Your CoffeeScript generates the following JavaScript:

$(".positive").numeric({
  negative: false
}, function() {}, alert("No negative values"), this.value = "", this.focus());

As you can see, it's not the same.

Please note some things:

  • You do not have to use CoffeeScript. You can use plain JavaScript if you want to.
  • If you want to use CoffeeScript, please read up on its syntax. Most importantly: in CoffeeScript, whitespace is significant.

Your codesnippet could look like this, in correct CoffeeScript:

$(".positive").numeric 
  negative: false
  -> 
    alert "No negative values"
    @value = ""
    @focus()

The reason that your code isn't executed when you put it through the asset pipeline, is that it will end up in the head of the document, instead of the body, and hence it will be executed before the browser has finished loading the DOM.

In other words - there isn't any element to fetch yet.

To solve this, wrap you code with JQuery:

$ ->
  # Your code goes here

JQuery will make sure that your code is executed only once the DOM is ready for manipulation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Jesper, I tried the coffee code you provided but it didn't work still, probably due to your explanation that the DOM wasn't loaded and no element could be found. I wasn't familiar with $-> but your explanation was clear enough that wrapping my code in $(document).ready(function(){ #my code here }); worked. Thank you!
You're welcome :) Regarding DOM loading: $(document).ready(function(){ #my code here }); is equal to $(function() {//your code here}) which is equal to $ -> #your code in CoffeeScript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.