apprentice_rails
apprentice_rails

Reputation: 19

function click() is not working [Rails 3.2 + jquery]

in my index.html.erb I have:

<button type="button" id="clean">Clean</button>

This button is add after by action "something.js.erb". So, in application.js:

$(function () {
    $('button#clean').click(function(){
        $('#target').remove(); 
    });
});

why is not working? When I put this script into html, it's work.

Upvotes: 1

Views: 1400

Answers (5)

Deepak Kumar
Deepak Kumar

Reputation: 578

Use "on function" in a correct format.

$(document).on('click', 'button#clean', function () {
    $('#target').remove();
});

Upvotes: 2

Sully
Sully

Reputation: 14943

If you want page specific js to be executed before going to the index.html for foo_controller then do

assets/javascripts/foo/index.js

and place

$(function () {
    $('button#clean').click(function(){
        $('#target').remove(); 
    });
});

Upvotes: 0

Sean3z
Sean3z

Reputation: 3735

I'd check your console to ensure there are no errors and ensure you've included application.js and jQuery within your HTML.

index.html.erb

<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/application.js"></script>

application.js

(function ($) {
  $('button#clean').click(function () {
    $('#target').remove();
  });
})(jQuery);

Upvotes: 0

Braunson
Braunson

Reputation: 717

Make sure your loading jQuery beforehand and I suggest using the following code

 $('button#clean').on("click", function() {
 });

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

Are you referencing your .js file in your HTML ??

Also Hit F12 to check for any errors in the console section

If you see no errors then try to attach the event handler using .on()

$('button#clean').on('click', function() {
});

Upvotes: 0

Related Questions