twitter bootstrap popover with rails - ruby-on-rails

Popovers do not seem to be working for me at the moment. I'm using the twitter-bootstrap gem for other functions successfully (like the carousel), and can see that tooltip and popovers are loaded in the page's source:
<script src="/assets/bootstrap-tooltip.js?body=1" type="text/javascript"></script>
<script src="/assets/bootstrap-popover.js?body=1" type="text/javascript"></script>
Here is my javascript (which I placed in application.js)
$(function () {
$('.popover-test').popover({ html : true });
});
Here is my what is in my view:
<%= link_to('Popover test', '#', :class => "popover-test", :title => "This is a test", "data-content" => "<b>hello popover world</b>") %>
Any help would be greatly appreciated, thank you!

You're not initialising the popover. Try:
$(function () {
$('.popover-test').popover({
html : true
}).popover('show');
});
Note the .popover('show')
I'd also recommend taking the content logic out of your html so your final result looks like:
$(function () {
$('.popover-test').popover({
html : true,
title: "This is a test",
content: "<b>hello popover world</b>"
}).popover('show');
});
...much cleaner

Try this markup:
<%= link_to('Popover test', '#', :class => "popover-test", :rel => "popover", :title => "This is a test", :"data-content" => "<b>hello popover world</b>") %>
You were just missing the :rel value, and "data-content" should be a symbol.

Did you get this working? If not, what wisew said is correct, however, he has a small typo -> remove the quotes around "data-content":
<%= link_to('Popover test', '#', :class => "popover-test", :rel => "popover", :title => "This is a test", :data-content => "<b>hello popover world</b>") %>
See if that does it

Related

ajax not working in my rails project

I'm trying to add an effect to my rails project using ajax. There's 4 divs on my page:
<div header></div>
<div menu></div>
<div content></div>
<div footer></div>
When a link in the menu div is clicked, the footer should slide up, and the new page text should appear in the content div. The code works fine when I have all the files in my public folder, in the rails project, but when I put files in the View folders, it doesn't work. Any idea why?
I have a scripts.js file in my assets/javascripts folder. The code is:
var ajax_loaded = (function(response) {
$("#content").slideUp(
"fast",
function() {
$("#content")
.html(response)
.slideDown("fast");
$("#content .ajax").on("click",ajax_load);
$("#content form").on("submit",form_submit);
});
});
var form_submit = (function(e) {
e.preventDefault();
var url = $(this).attr("action");
var method = $(this).attr("method");
var data = {}
$(this).find("input, textarea").each(function(i){
var name = $(this).attr("name");
var value = $(this).val();
data[name] =value;
});
$.ajax({
"url": url,
"type": method,
"data": data,
"success": function () {
history.pop();
$(history.pop()).trigger("click");
},
"error": function () {alert("bad");}
});
});
var history = [];
var current_url_method;
var ajax_load = (function(e) {
e.preventDefault();
history.push(this);
var url =$(this).attr("href");
var method = $(this).attr("data-method");
if (current_url_method != url + method) {
current_url_method = url + method;
$.ajax({
"url": url,
"type": method,
"success": ajax_loaded,
});
}
});
$("#menu a").on("click",ajax_load);
$("#menu a.main").trigger("click");
I have a style.css.scss in my assets/stylesheets folder. The code is:
#header {
background: #333333;
height:50px;
}
#menu {
background: #ffffff;
}
#content { background: #eeeeee;height:100px;}
#footer {
background: #333333;
color: #ffffff;
height: 100px;
}
In my routes folder I have:
Books::Application.routes.draw do
get "about_us", :to => "static_pages#about_us"
get "contact_us", :to => "static_pages#contact_us"
get "invite_us", :to => "static_pages#invite"
get "faq", :to => "static_pages#faq"
root :to => 'books#index'
Index method in the Books controller is:
def index
render :layout => "application"
end
In my Views/layouts, in application.html.erb, I have (this change a bit from my public folder, where links were of the form About Us):
<!DOCTYPE html>
<html>
<head>
<title>Books</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<div id = "header">My header</div>
<div id = "menu">
<%= link_to "About Us",about_us_path,:class => "main" %>
<%= link_to "FAQ", faq_path, :class => "main" %>
<%= link_to "Invite Others", invite_us_path, :class => "main" %>
<%= link_to "Contact Us", contact_us_path, :class => "main" %>
</div>
<div id = "content">
<%= yield %>
</div>
<div id = "footer">My footer</div>
<script src = "http://code.jquery.com/jquery-1.9.1.min.js">
</script>
</body>
</html>
Anyway, if you have any ideas on what's wrong, I'd be grateful, thanks. Like I said, it wokrs in the public folder, so I think my scripts.js is ok. Could it be something to do with the ':class => "main" ' part?
You may want to make sure scripts.js is being served when you load the page. I see that you include application.js in your layout file. This file is used as a manifest file in the Rails asset pipeline, so make sure it's configured to include scripts.js when it loads. It will need to have a line like this:
//= require scripts
In a browser, assuming you are running a rails server on port 3000, you can make sure your scripts file is accessible by visiting http://localhost:3000/assets/scripts.js. You can make sure it's included in application.js by visiting http://localhost:3000/assets/application.js.
More information on the asset pipeline: http://guides.rubyonrails.org/asset_pipeline.html
Hope this helps.
got it sorted. I wrapped all the code in my scripts.js in a
$(document).on("ready", function(){......});
That was the main thing.
Also, I was calling the jquery library twice, which probably didn't help - //= require jquery, in my application.js.erb file, and also from my application.html.erb.
Anyway, the case is resolved! Thanks for everything.

Dynamic select with onchange function calling to jquery with ajax

PLease help , I used some examples to build dynamic select, but it does not seem to work , nevertheless in console I can see 200 status, I am not fluent so please please help, The problem is that list in the select will not decrease, it shows same options after choosing previos
index.html.erb
<%= collection_select(nil, :site_id, #sites, :id, :name, {:prompt => "Select a Site"}, { :id => "sites_select"}) %>
<br/>
<%= collection_select(nil, :floor_id, #floors, :id, :name, {:prompt => "Select a Floor"}, {:id => "floors_select"}) %>
<br/>
<%= collection_select(nil, :pod_id, #pods, :id, :name, {:prompt => "Select a pod"}, {:id => "pods_select"}) %>
<script>
$(document).ready(function() {
$('#sites_select').change(function() {
$.ajax({
url: "<%= update_floors_path %>",
data: {
site_id : $('#sites_select').val()
},
dataType: "script"
});
});
$('#floors_select').change(function() {
$.ajax({
url: "<%= update_pods_path %>",
data: {
floor_id : $('#floors_select').val()
},
dataType: "script"
});
});
});
</script>
devices_controller.rb
def update_floors
# updates floors and pods based on genre selected
site = Site.find(params[:site_id])
# map to name and id for use in our options_for_select
#floors = site.floors.map{|a| [a.name, a.id]}.insert(0, "Select a Floor")
#pods = site.pods.map{|s| [s.name, s.id]}.insert(0, "Select a Pod")
end
def update_pods
# updates pods based on floor selected
floor = Floor.find(params[:floor_id])
#pods =floor.pods.map{|s| [s.name, s.id]}.insert(0, "Select a Pod")
end
update_floors.js.erb
$('#floors_select').html("<%= escape_javascript(options_for_select(#floors)) %>");
$('#pods_select').html("<%= escape_javascript(options_for_select(#pods)) %>");
update_pods.js.erb
$('#pods_select').html("<%= escape_javascript(options_for_select(#pods)) %>");
routes.rb
get 'devices/update_floors', :as => 'update_floors'
get 'devices/update_pods', :as => 'update_pods'
root :to => "devices#index"
Appreciate any suggestion
Thank you,
D
Seems new loaded JavaScript not adding effects to parent page. Why not do the $().html inside the Ajax success callback. And make the update.js.html page only contains the options for select. Should work.
javascript:
$("#sites_select").change(function(){
$.ajax({
url: your_url,
//orther options ...
success: function(data){
$("#floors_select").html(data);
}
});
});
and in your update_floors.js.html
<%=options_for_select(#floors)%>
Do the same for update pods. :)
Problem is with your controller,
You have not mentioned the respond_to js block any where in the code,
Just put this code in both update methods,
respond_to do |format|
format.js
end
Give the response format in the controller respond_to :js, :only=>[:update_floors,:update_pods ]
Apart from that write the following into update_floors.js.erb file.
$('#floors_select').html("<%= escape_javascript(collection_select(:your_object_name, :floor_id, #floors.to_a, :id, :name, :prompt=>"Select a Floor")) %>");
I think the above will work.

gmaps4rails single marker auto zoom

I am trying to follow the answer here to zoom out a bit (by default) when a single marker is displayed on the map. I have tried the code below, and have a working map generating, but changing setZoom has no effect. Also, I receive the following error from firebug (below code).
<%= gmaps("markers" => {"data" => #json, "options" => {"auto_zoom" => false} }) %>
<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
function gmaps4rails_callback() {
if (Gmaps4Rails.markers.length == 1) {
//only one marker, choose the zoom level you expect
Gmaps4Rails.map.setZoom(5);
}
else{
//more than one marker, let's auto_zoom
Gmaps4Rails.map_options.auto_zoom = true;
Gmaps4Rails.adjust_map_to_bounds();
}
}
</script>
<% end %>
The only error says:
TypeError: Yc is not a function
[Break On This Error]
...=b}Rf[F].Fa=xk(7,Yc("f"));me[F].cb=xk(3,function(a){var b;if(b=a.ca[ec]()?j:a.ca...
Ok, the interface changed a lot since I posted the answer you quote.
<%= gmaps("markers" => {"data" => #json, "options" => {"auto_zoom" => false} }) %>
<% content_for :scripts do %>
<script type="text/javascript" charset="utf-8">
Gmaps.map.callback = function() {
if (Gmaps.map.markers.length == 1) {
//only one marker, choose the zoom level you expect
setTimeout(function() { Gmaps.map.serviceObject.setZoom(5);}, 50);
}
else{
//more than one marker, let's auto_zoom
Gmaps.map.map_options.auto_zoom = true;
Gmaps.map.adjustMapToBounds();
}
}
</script>
<% end %>

Refresh div with gmaps4rails (AJAX)

I'm using Rails 3.0.9 version, and jquery.
I've been using this gem without a database. It is used only for map display, and display KML file on it. For this I used:
<div id='ajax_map'>
<% #kmlurl="http://mysite/file1.kml" %>
<%= gmaps( :kml => { :data => "[{ url: #{#kmlurl.inspect}}]" } ) %>
</div>
All great shows.
I want to do that after you change the links (# kmlurl), and click on the button, the map updated with this new KML file. I use a separate action js.erb with the following code:
$('#ajax_map').html('<%= #kmlurl="http://mysite/file2.kml" %>'+'<br />'+'<%= gmaps( :kml => { :data => "[{ url: #{#kmlurl.inspect}}]" } ) %>');
But he does not update the DIV. "js.erb" rendered normally, without using the method of gmaps () it normally returns # kmlurl. I tested this same code in the ". Html.erb" in the tags , it loads a new file, but, of course, just when the page loads.
How can I solve this problem?
Solved the problem as follows (in js.erb):
$('#ajax_map').html('<%= escape_javascript( gmaps({:last_map => false}) ) %>');
Gmaps.map = new Gmaps4RailsGoogle();
Gmaps.load_map = function() {
Gmaps.map.map_options.maxZoom = 15;
Gmaps.map.initialize();
Gmaps.map.kml = [{ url: '<%= "#{#kmlurl}" %>'}];
Gmaps.map.create_kml();
Gmaps.map.adjustMapToBounds();
Gmaps.map.callback();
};
Gmaps.loadMaps();
First I would refactor things just a bit.
Say that first bit of code were in your index page. I'd move the setting of #kmlurl into the corresponding controller action:
def index
#kmlurl = "http://mysite/file1.kml"
end
Then (assuming index?) your index view would be simply:
<div id="ajax_map">
<%= gmaps( :kml => { :data => "[{ url: #{#kmlurl}}]" } ) %>
</div>
Then to add a link that will update the map:
<%= link_to 'Other Map', '/othermap', :remote=>true %>
Now you'd create a route in routes.rb:
match '/othermap' => 'foo#othermap'
Then in foo_controller.rb:
def othermap
#kmlurl = "http://mysite/file2.kml"
end
Then create othermap.js.erb:
$('#ajax_map').html(
'<%=
escape_javascript(
gmaps( :kml => { :data => "[{ url: #{#kmlurl}}]" } )
)
%>'
)
That's a quick fix, but what I would REALLY do is strive to make your view code as simple as possible, and do all the real work in the controller. Ideally your view would just be:
<div id="ajax_map">
<%= gmaps( :kml => { :data => #mapdata } ) %>
</div>
set up #mapdata as appropriate in your controller. You've got too much stuff that really belongs in a controller embedded in your view code! Your othermap.js.erb should be equally simplified. i.e.
$('#ajax_map').html('<%= escape_javascript(gmaps( :kml => { :data => #mapdata } ))%>')

Adding an onclick option to link_to method in rails?

I want to add an onclick option to link_to method for loading an modal dialog box...i am using rails version 2.3.8 and i searched on google and could not do it. Plz anybody help me?
My link_to method as follows.
<%= link_to 'All countries',{:controller=>'countries', :action=>'new'}, :remote => true %>
If you are using 2.3.8, you don't have :remote => true. You need to use link_to_remote if you are try to do an ajax action.
So it would look something like:
<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}%>
<div id="populate_me"></div>
and your new method would have to handle the ajax request with something like
countries_controller.rb
def new
<do something>
render :update do |page|
page.replace_html 'populate_me', :partial => 'whatever'
end
end
UPDATED
If you want the onclick in addition to the ajax action, you can just pass it into the html options:
<%= link_to_remote 'All countries', :url => {:controller => 'countries', :action => 'new'}, :html => {:onclick => 'alert("some javascript executed before ajax")'} %>
You can add this to the link:
, :class => "pop light", :id => "modal_link"
Then, your JS shows something ilke this:
<script type="text/javascript">
$(document).ready(function() {
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('');
$('a.close').hide();
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
$('body').append('<div id="fade"></div>');
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
return false;
});
$('a.close').live('click', function() {
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
});
return false;
});
$('#modal_link').click();
});
</script>

Resources