rails tag embedded in html issues - javascript

<div class="well original3">
<%= form_tag( { :controller => 'businesses', :action => 'create' }, { :id => 'myform',:class => 'form-inline offset3', :method => 'post'}) do %>
<%= text_field_tag('mnum' ,nil, :class => "input-xlarge", :style => "text- align:center;height:28px;",:placeholder => "Enter Mobile Number") %>
<%= submit_tag "Get", :id => "da",:class => "btn btn-large btn-primary" %>
<%end%>
</div>
JQUERY
$(document).ready(function () {
$("#da").click(function() {
//$(".original3").fadeOut(300, function() {
//$(".original3").css("display", "block");
$(".checked3").css("display", "block");
$(".checked3").show();
//});
});
});
Basically another Div will be hide via css. when click this Get button that div should show, But here is the problem when i click the GET button the the other div will show and fadeout soon. But when i change the GET button type submit to button that will work properly..?
How to avoid this problem...?
Thank you

Use
<%= submit_tag "Get", :id => "da",:onclick => show_checked3();,:class =>"btn btn-large btn-primary" %>
function show_checked3(){
$(".checked3").css("display", "block");
$(".checked3").show();
}
Or Try with
$(document).ready(function () {
$("#da").live('click',function() {
$(".checked3").css("display", "block");
$(".checked3").show();
//});
});
Update
You can try with
$("#myform").submit(function(){
$(".checked3").css("display", "block");
$(".checked3").show();
return true;
});

Related

Rails Ajax Refresh Partial while persisting params

I have a Rails app with a controller/view called "calls". Here is the basic controller action for index:
calls_controller.rb
def index
if params[:region].present?
#assigned = Call.where(region_id: params[:region][:area]).assigned_calls.until_end_of_day
#unassigned = Call.where(region_id: params[:region][:area]).unassigned_calls.until_end_of_day
else
#assigned = Call.assigned_calls.until_end_of_day
#unassigned = Call.unassigned_calls.until_end_of_day
end
end
Here are my views:
index.js.erb
$('#active').html("<%= escape_javascript render :partial => 'calls/assigned_calls', :locals => {:assigned_calls => #assigned} %>");
$('#inactive').html("<%= escape_javascript render :partial => 'calls/unassigned_calls', :locals => {:unassigned_calls => #unassigned} %>");
$(".select").select2({
placeholder: "Select One",
allowClear: true
});
index.html.erb
<div id="active">
<%= render "assigned_calls" %>
</div>
<div id="inactive">
<%= render "unassigned_calls" %>
</div>
<script>
$(document).ready(function() {
setInterval(function () {
$.ajax('calls/<%= params[:region][:area] %>');
} , 5000);
});
</script>
_assigned_calls.html.erb (view code omitted)
<%= form_tag calls_path, :method => 'get' do %>
<p>
<%= select_tag "region[area]", options_from_collection_for_select(Region.order(:area), :id, :area, selected: params[:region].try(:[], :area)), prompt: "Choose Region" %>
<%= submit_tag "Select", :name => nil, :class => 'btn' %>
So what's happening is on page load if I do not have the params of :region passed it sets the calls without being scoped by region. If region_id is present then it scopes calls where region_id is "1" or whatever the Region ID is that is passed from the submit_tag.
This works fine in the controller and view, however here's my problem. My index.html.erb I need to refresh the partials WITHOUT disturbing the params passed. So on setInterval I need to figure out how to reload the partials while persisting the params passed in the URL.
I tried to figure this out using a setInterval method but I'm not sure what I'm doing here 100%.
Can someone give me some advice on how to refresh the partials every 5 seconds while persisting the params so my instance variables persist through refresh?
If you need more context and/or code please let me know.
Update
Trying to rework the javascript based off an answer from a user and here's what I have.
<script>
$(document).ready(function() {
setInterval(function () {
$.ajax({
url: 'calls_path',
type: "GET",
data: { "region": '<%= #region.html_safe %>' }
}), 5000);
});
});
</script>
The page will load but when it tried to trigger in the chrome inspector I get:
calls?utf8=✓&region[area]=3:2901 Uncaught SyntaxError: Unexpected token )
Maybe this is a JS syntax error or I'm not closing the function properly.
If I understood properly, you want to have your parameters somehow pipelined through AJAX call to your controller, back to your js.erb file where it refreshes the partials?
My advice is to set passed parameters as instance variables in your controller like this:
calls_controller.rb
def index
if params[:region].present?
#region = params[:region]
#assigned = Call.where(region_id: params[:region][:area]).assigned_calls.until_end_of_day
#unassigned = Call.where(region_id: params[:region][:area]).unassigned_calls.until_end_of_day
else
#assigned = Call.assigned_calls.until_end_of_day
#unassigned = Call.unassigned_calls.until_end_of_day
end
end
Now your #region instance variable will be available in your index.js.erb
where you can pass it to other partials you are trying to render.
index.js.erb
$('#active').html("<%= escape_javascript render :partial => 'calls/assigned_calls', :locals => { :assigned_calls => #assigned, :region => #region } %>");
$('#inactive').html("<%= escape_javascript render :partial => 'calls/unassigned_calls', :locals => { :unassigned_calls => #unassigned, :region => #region } %>");
_assigned_calls.html.erb
<%= form_tag calls_path, :method => 'get' do %>
<%= select_tag "region[area]", options_from_collection_for_select(Region.order(:area), :id, :area, selected: region.try(:[], :area)), prompt: "Choose Region" %>
<%= submit_tag "Select", :name => nil, :class => 'btn' %>
<% end %>
Also, I think that better practice in your index.html.erb script tag
is to do it like this:
<script>
$(document).ready(function() {
setInterval(function () {
$.ajax({
url: 'calls_path',
type: "GET",
data: { "region": '<%= #region.html_safe %>' }
});
}, 5000);
});
</script>
Please test this out if you're interested and get back to me :)

Open modal on page load - RoR and Jquery

I have a link inside a form that opens a modal:
<% if action_name == "new" %>
<div>
<%= link_to 'Open Modal', search_samples_samples_path, {:remote => true, 'data-toggle' => "modal", 'data-target' => '#modal-window'} %>
</div>
<% end %>
What I want to do now is, when the form opens/loads, open the modal directly, without having to click the link.
What's the best way to do this?
Thanks for your suggestions, it worked with:
$(document).ready(function() {
document.getElementById('pcrmodal').click();
});
And I added the "id" part to the link element, and hide it also (with display:none):
<%= link_to 'PCR Anterior?', search_samples_samples_path, {:remote => true, 'data-toggle' => "modal", 'data-target' => '#modal-window', 'id' => 'pcrmodal', 'style' => 'display:none'} %>
Thanks again for your feedback.
Simply use .modal() function provided by bootstrap if you are using that
$("#modal-window").modal()

Dropdown with :remote=>true links not rendering ajax partial in Rails 3.2

After looking around for an answer to my problem for some time I have now come to the conclusion that I need to ask my first ever question on SO. I hope you can help!
As you can see below I have a list with links that via ajax renders different partials when clicked. Everything here worked fine, until I decided to change the list to a dropdown-list with javascript (with some help from http://tympanus.net/codrops/2012/10/04/custom-drop-down-list-styling/).
All the functionality in the dropdown works except the "link_to :remote => true"-part. Nothing at all happens when the links in the dropdown are clicked. I know that the main problem is in the dropdown.js code, but as I'm fairly new to programming I simply cannot find a solution.
Question?
So basically, how do I make the links in my dropdown render my
partials with ajax?
Views/products/Index.html.erb
<div id="proftab" class="wrapper-dropdown">
<span>Popular</span>
<ul class="dropdown">
<li><%= link_to "Popular", products_index_path(:feed => "popular"), :remote => true%></li>
<li><%= link_to "Following", products_index_path(:feed => "following"), :remote => true%></li>
<li><%= link_to "Sales", products_index_path(:feed => "sales"), :remote => true%></li>
<li><%= link_to "Expensive", products_index_path(:feed => "expensive"), :remote => true%></li>
<li><%= link_to "Trendspotter", products_index_path(:feed => "trendspotter"), :remote => true%></li>
</ul></div>
<div class="row">
<div id="profile">
<!-- The rendering is going on here -->
</div>
Controllers/products_controller.erb
def index
case params[:feed]
when "sales"
#products = #Different scopes
when "expensive"
#products = #Different scopes
when "trendspotter"
#products
when "following"
#products = #Different scopes
else
#products = #Different scopes
end
respond_to do |format|
format.html
format.js
end
end
Views/products/index.js.erb
<% if params[:feed] == 'sales' %>
$("#profile").html("<%= escape_javascript(render(:partial => 'sales')) %>");
<% elsif params[:feed] == 'following' %>
$("#profile").html("<%= escape_javascript(render(:partial => 'following')) %>");
<% elsif params[:feed] == 'expensive' %>
$("#profile").html("<%= escape_javascript(render(:partial => 'expensive')) %>");
<% else %>
$("#profile").html("<%= escape_javascript(render(:partial => 'popular')) %>");
<% end %>
Routes.rb
root :to => 'products#index', :constraints => lambda{|req| !req.session[:user_id].blank?}
root :to => 'pages#home'
Assets/javascript/dropdown.js AKA the problem
function DropDown(el) {
this.proftab = el;
this.placeholder = this.proftab.children('span');
this.opts = this.proftab.find('ul.dropdown > li');
this.val = '';
this.index = -1;
this.initEvents();
}
DropDown.prototype = {
initEvents : function() {
var obj = this;
obj.proftab.on('click', function(event){
$(this).toggleClass('active');
return false;
});
obj.opts.on('click',function(){
var opt = $(this);
obj.val = opt.text();
obj.index = opt.index();
obj.placeholder.text(obj.val);
});
},
getValue : function() {
return this.val;
},
getIndex : function() {
return this.index;
}
}
$(function() {
var proftab = new DropDown( $('#proftab') );
$(document).click(function() {
// all dropdowns
$('.wrapper-dropdown').removeClass('active');
});
});

AJAX function not getting called

I am new to RoR and AJAX, jquery etc. I am trying to make an ajax call in a view, but its not happening.
Corresponding controller(product_search_controller,rb) is:
def index
#products = querySolr(params[:q])
#productsProxy = Array.new
if #products != nil
#products.each do |p|
#productsProxy.push(ProductProxy.new(p))
end
else
#productProxy = []
end
#taxons = #productsProxy.map(&:get_taxonomy).compact.uniq
respond_with("Search Results") do |format|
format.js
format.html
format.xml { render :xml => #productsProxy, :only => [:name, :permalink, :description, :mrp], :methods => [:designer, :taxons, :price] }
end
end
Corresponding view(views/product_search/index.hrml.erb) is:
<%= render :partial => 'products', :locals => {:products => #productsProxy, :taxons => #taxons, :scope => self, :scope_type => "Search"} %>
<%= render :partial => 'shared/inf_scroll', :locals => {:url => "?&page=", :total_count => #total_count} %>
/views/product_search/_products.html.erb:
<% if products.empty? %>
<div class="not_found"><%= "No Products found for the selected query. Please try a different search." %></div>
<% elsif params.key?(:keywords) %>
<h3><%= t(:search_results, :keywords => h(params[:keywords])) %></h3>
<% end %>
<% if products.any? %>
<div class="product_rows">
<%= render :partial=> 'product_listing_feature', :locals => {:scope => scope, :scope_type => scope_type} %>
<div id="ql_product"></div>
<%taxons.each do |taxon|%>
<ul class="products" data-hook class="products">
<div class = "product_row">
<h1><%=taxon%></h1>
<% taxonProducts = Array.new %>
<% products.each do |product| %>
<%#ptaxon = product.get_taxonomy%>
<%if #ptaxon == taxon%>
<% taxonProducts.push(product) %>
<% end %>
<% end %>
<div class ="featured_product_list">
<ul class = "featured_products">
<div class = "page">
<%= render :partial=> 'product_listing', :locals=>{:collection=> taxonProducts} %>
</div>
</ul>
</div>
</div>
</ul>
<% end %>
</div>
</div>
<% end %>
i.e it renders another partial _product_listing which has the following script:
<script>
$("document").ready(function(){
$("li#product_<%=product.productId%>").hover(
function(){$("div#quick_look_<%=product.productId%>").css("visibility", "visible");},
function(){$("div#quick_look_<%=product.productId%>").css("visibility", "hidden");}
);
$("div#quick_look_<%=product.productId%>").css("visibility", "hidden");
});
hide_sold_out({
url: "<%= sold_out_status_taxons_url(#taxon) %>",
data: {
pids: "<%= collection.map(&:id).join(",") %>"
}
});
</script>
Helper:
var hide_sold_out = function(options){
$.ajax({
url: options["url"],
data: options["data"],
type: 'get',
dataType: 'text',
success: function(data){
pids = data.split(',');
for(var i = 0; i < pids.length; i++) {
if($("li#product_"+pids[i]).children("div.info").children("span.offer.sold").length == 0) {
$("li#product_"+pids[0]).children("div.info").append("<span class='offer sold'></div>");
$("li#product_"+pids[0]).children("div.info").children("div.product_listing_info_hover").children("div.listing_buttons").html("");
}
}
},
error: function(data){
console.log(data);
}
. I tried using the following in /views/product_search/index.js.erb:
$("ul.products").append("<div class='page'><%= escape_javascript(render(:partial => 'product_listing', :locals=>{:collection=> #productsProxy})) %></div></div>")
This didn't work. Then i tried:
<%#taxons.each do |taxon|%>
<%taxonProducts = Array.new%>
<%#productsProxy.each do |product|%>
<%#ptaxon=product.get_taxonomy%>
<%if #ptaxon==taxon%>
<%taxonProducts.push(product)%>
<%end%>
<%end%>
$("ul.products").append("<div class='page'><%= escape_javascript(render(:partial => 'product_listing', :locals=>{:collection=> #taxonProducts})) %></div></div>")
<%end%>
But the AJAX call is not doing what its supposed to do. Please could someone help me debug this. Thanks
These
url: options["url"],
data: options["data"],
should be
url: options.url,
data: options.data,

Enable/disable nested form fields with javascript

I have a nested form with checkboxes and text fields. I would like to be able to have the text fields only be enabled if the text box for that specific nested form is clicked/enabled. It is currently hard coded to enable/disable fields if the "custom" text box is set. How can I have javascript update these textbox attributes on the fly?
Form.erb now
<%= simple_nested_form_for #client do |f| %>
<%= f.fields_for :client_prices do |def_price_form| %>
<div class="controls controls-row">
<div class='span10'>
<% if def_price_form.object.custom == true %>
<%= def_price_form.input :custom, :wrapper_html => { :class => 'span1' } %>
<% end %>
<%= def_price_form.input :visit_type, :wrapper_html => { :class => 'span2' } %>
<%= def_price_form.input :price, :wrapper => :prepend, :wrapper_html => { :class => 'span2' }, :label => "Price" do %>
<%= content_tag :span, "$", :class => "add-on" %>
<%= def_price_form.input_field :price %>
<%= def_price_form.link_to_remove '<i class="icon-remove"></i>'.html_safe, :class => 'btn btn-danger', :wrapper_html => { :class => 'span3 pull-left' } %>
<%end%>
<% else %>
<%= def_price_form.input :custom, :hidden => false, :wrapper_html => { :class => 'span1' } %>
<%= def_price_form.input :visit_type, disabled: true, :wrapper_html => { :class => 'span2' } %>
<%= def_price_form.input :price, :wrapper => :prepend, :wrapper_html => { :class => 'span2' }, :label => "Price" do %>
<%= content_tag :span, "$", :class => "add-on" %>
<%= def_price_form.input_field :price, disabled: true %>
<%end%>
<%end%>
</div>
</div>
<% end %>
<%= f.link_to_add "Add a custom price", :client_prices, :class => 'btn btn-success' %>
<p> </p>
<div class="controls">
<%= f.button :submit, :class => 'btn btn-primary' %>
</div>
<% end %>
HTML generated by RoR here
http://jsfiddle.net/59AXJ/
This gets the attribute name from the checkbox that is clicked. Then finds inputs that have similar names, those are the inputs that we will toggle "disabled".
$("input[type='checkbox']").click(function () {
var thisCheckbox = $(this);
var id = $(this).attr("id");
var text = $("label[for=" + id + "]").text().toLowerCase();
var name = $(this).attr("name").replace("[" + text + "]", "");
$("input[name*='" + name + "']").each(function () {
var thisInput = $(this);
if (thisInput.attr("disabled")) {
thisInput.removeAttr("disabled");
} else {
thisInput.attr("disabled", "disabled");
thisCheckbox.removeAttr("disabled");
}
})
});
http://jsfiddle.net/Sbw65/ <-- test it out
As I know, it's impossible to make this on fly, but you can write some unique function on javascript, wich will connect some input with some checkbox by their css class. Something like this (code on CoffeeScript):
changeCheckbox: (class_value) =>
$('[type=checkbox] '+class_value)). on 'check', (e) ->
$input = $(e.currentTarget)
if !$input.prop("checked")
$("input "+class_value).prop('disabled', false)
else
$("input "+class_value).prop('disabled', true)
After that, you just need to add some class for connected checkbox and inputs.

Categories