Reputation: 234
I have a model name Area and in the index I would like to load the area_path(area) inside a div instead of sending people to a different page.
This are the codes I have so far:
<h3>World Map</h3>
<script>
$(document).ready(function(){
$("area").click(function(){
$("#div1").load("<%= area_path(area) %>");
});
});
</script>
<div class="map">
<%= image_tag("strangemap.png", :usemap => "#worldmap", :class => "mapper") %>
<map name="worldmap">
<% @areas.each do |area| %>
<area shape="poly" coords="<%= area.coords %>"
class="target noborder"
data-textbox<%= area.box_location %>="<%= area.name %>">
<% end %>
</map>
</div>
<div class="map_help" id="div1"></div>
areas_controller.rb
class AreasController < ApplicationController
def show
@area = Area.find(params[:id])
end
def new
@area = Area.new
end
def create
@area = Area.new(area_params)
if @area.save
flash[:success] = "Area successfully saved!"
redirect_to @area
else
render 'new'
end
end
def index
@areas = Area.all
end
private
def area_params
params.require(:area).permit(:name, :coords, :box_location, :description,
:creator, :diff_from, :diff_to)
end
end
Of cause the codes don't work because the variable "area" is not define inside the script. I can make it SORTA work by moving the script inside the loop, but the result is kind of wacky. For example it will try to load every area inside the model then settle to the first one :)
Any help will be appropriated!
Upvotes: 0
Views: 236
Reputation: 11
Hi you can use closest element value. like below.
<script>
$(document).ready(function(){
$("area").click(function(){
$("#div1").load($(this).closest("map").find('.area-path').text());
});
});
</script>
<div class="map">
<%= image_tag("strangemap.png", :usemap => "#worldmap", :class => "mapper") %>
<map name="worldmap">
<% @areas.each do |area| %>
<area shape="poly" coords="<%= area.coords %>"
class="target noborder"
data-textbox<%= area.box_location %>="<%= area.name %>">
<% end %>
<span class = "area-path"><%= area_path(area) %></span>
</map>
</div>
Upvotes: 1
Reputation: 133403
You can use custom data-*
prefixed attribute to store the area_path(area)
<map name="worldmap">
<% @areas.each do |area| %>
<area shape="poly" coords="<%= area.coords %>"
class="target noborder"
data-textbox<%= area.box_location %>="<%= area.name %>"
data-path="<%= area_path(area) %>"
>
<% end %>
</map>
Then in the script use HTMLElement.dataset property or .data()
to read the custom data-*
prefixed attribute value.
$("area").click(function(){
$("#div1").load(this.dataset.path); //or, $(this).data('path')
});
Upvotes: 1