user3301201
user3301201

Reputation:

calling a jquery function through button_to in ruby on rails

Below is the code of a button i n ruby on rails

<%= button_to "btnAdd"%> 

and below is the jquery function:

<script type="text/javascript">
 $(document).ready(function() {
            $("#btnAdd").click(function() {
              alert("Hassan")
        });
</script>

I want to call jquery function through button. But its not going into the jquery function, why. Kindly reply me. Thanks

Upvotes: 1

Views: 1301

Answers (2)

Pavan
Pavan

Reputation: 33552

The problem is you haven't set an id for your button.Try this:

<div id="btn">
  <%= button_to "btnAdd" %>
</div>

#=> <input type="submit" value="btnAdd" id="btn" />

Change your Jquery like this:

$(document).ready(function() {
     $("#btn").click(function(event) {
         event.preventDefault();
      alert("Hassan");
    });
});

Fiddle

Upvotes: 0

Kiran
Kiran

Reputation: 20303

button_to generates a form with a input type="submit" button like:

<%= button_to "btnAdd"%>
# => "<form method="post" action="" class="button_to">
#      <div><input value="btnAdd" type="submit" /></div>
#    </form>"

So try this:

$(document).ready(function() {
     $("input[value='btnAdd']").click(function(e) {
      e.preventDefault();
      alert("Hassan");
    }
});

DEMO

Upvotes: 1

Related Questions