Reno
Reno

Reputation: 2982

Rails link_to image_tag - getting the href value on click with jQuery

Rails 2.3.5

For a link_to image_tag', I've been trying to figure out how to grab the href with jQuery. I assume it has nothing to do with Rails and me doing something wrong using jquery. All the examples I've found for a link indicate there should be an href attribute when you grab the link at click time. Say if I put the id just inside the image_tag block or the other way around (or an :id in both blocks). Like, neither of these would work (the alert returns 'undefined'):

  <%= link_to image_tag("apple.png", :size => "60x50", :alt => "New Apple",
        :id => 'new_apple', :class => 'item_images'),
        :controller => :items, :action => :new,  :item_type =>  'apple' %>

$('#new_apple' ).click(function(){
    alert($(this).attr("href"));
   ...

}   

or

  <%= link_to image_tag("apple.png", :size => "60x50", :alt => "New Apple",
        :id => 'new_apple', :class => 'item_images'), :id => 'my_new_apple'
        :controller => :items, :action => :new,  :item_type =>  'apple' %>



    $('#my_new_apple).click(function(){
        alert($(this).attr("href"));

       ...

}

Basically I'm trying to grab the href to use in an AJAX request (kind of like how you can grab a button submit action and use it's URL and TYPE for the request. I haven't found an example of the structure to for an ajax request based off a link click yet (still looking).

Thanks for any help!

Upvotes: 0

Views: 7202

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 96914

The second excerpt should work but you're missing a closing quote and your link_to is wrong:

<%= link_to(image_tag("apple.png", :size => "60x50", :alt => "New Apple", :id => 'new_apple', :class => 'item_images'),
    { :controller => :items, :action => :new, :item_type => 'apple' },
    :id => 'my_new_apple') %>

$("#my_new_apple").click(function() {
  alert($(this).attr("href"));
}

You can also try with the first link_to:

$("#new_apple").click(function() {
  alert($(this).parent().attr("href"));
}

Upvotes: 4

Related Questions