How do I use jQuery in Ruby on Rails 3.2?

I am a newbie in Ruby on Rails and need to know what things we have to be careful about if we are willing to use jQuery in a Ruby on Rails application.

In my view page I have:

<script type="text/javascript" src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<%= javascript_include_tag "application" %>
<script>
    alert("hussain")
    alert($('#hussi').val())
</script>

It gives the first alert as expected, but for the second alert it says '$' is not defined.

I have the jquery-rails gem installed.

The browser points out that I have a missing reference in my application.js file.

  require jquery;
  require jquery_ujs;

I saw some file examples where they mention it like:

= require jquery;
= require jquery_ujs;

But adding'=' raises an IDE error in my IDE.

Upvotes: 0

Views: 7254

Answers (2)

Sijmen Mulder
Sijmen Mulder

Reputation: 5819

There is a typo in your code: text/javas c ript. This causes the script to not be parsed.

Upvotes: 0

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22296

Add this to you application.js:

//= require jquery
//= require jquery_ujs

and add this to your Gemfile:

gem 'jquery-rails'

Also make sure you have this in you application layout:

<%= javascript_include_tag "application" %>

Just a note: avoid using tags in your code, move your javascript to your assets folder.

Upvotes: 1

Related Questions