I am using will_paginate in order to list huge number of files. I also have a check_box in order to choose files for the futher analysis.
To save the ids in the cookie while changing the pages I used following javascript:
<script src="/assets/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
var checkedIds = []
$('.checkmeplease').on("change", function(){
if($(this).is(':checked')) {
checkedIds.push($(this).val())
}
else {
checkedIds.splice(checkedIds.indexOf($(this).val()), 1);
}
$.cookie('checked_file_ids', checkedIds,{path:'/'});
});
</script>
My checkboxes:
<% #files.each do |file| %>
<p><td> <%= check_box_tag "files[]", file.id,false,:class=>'checkmeplease' %></td> <%= file.name %></p>
<%end%>
It saves the IDs but when I change the page with will_pagination, the saved IDs disappear.
I was introduced as well this code:
<script type="text/javascript">
var checkedIds = $.cookie('checked_file_ids');
$('p td input[type=checkbox]').on('change', function () {
if($(this).is(':checked')) {
checkedIds.push($(this).val())
}
else {
checkedIds.splice(checkedIds.indexOf($(this).val()), 1);
}
$.cookie('checked_file_ids', checkedIds);
})
</script>
But $('p td input[type=checkbox]').on('change', function () does not seem to work.
Where is my mistake? How can I save the IDs from the previous pages as well?
Thanks a lot.
Use your first example, but instead of this line:
var checkedIds = []
Use this line from your second example.
var checkedIds = $.cookie('checked_file_ids');
The problem I see with the first example is that you never load the previously saved ids from the cookie. So, come page two, when you check some, you're overwriting the previous values.
Related
im a student, not too experienced with coding. trying to make a software solution for my class, and having some problems with running <%...%> tags inside functions that are in tags in an ejs HTML file.
<script>
//grab elements
const textBox = document.querySelector(".lineBox");
const nextLine = document.querySelector(".nextLine");
const prompt = document.querySelector(".question");
//display starting script line
textBox.innerHTML = "<%= JSON.stringify(scripts[scriptName][counter][0]) %>";
//nextline function
function updateLine() {
<% counter = counter + 1; %>
if ("<%= JSON.stringify(scripts[scriptName][counter][0]) %>" == 1) {
<% counter = counter + 1; %>
}
textBox.innerHTML = "<%= JSON.stringify(scripts[scriptName][counter][0]) %>";
}
//prompt line function
function promptLine() {
<% counter = counter + 1; %>
textBox.innerHTML = "<%= JSON.stringify(scripts[scriptName][counter][0]) %>";
}
//call functions onclick
nextLine.onclick = updateLine;
prompt.onclick = promptLine;
</script>
I am currently making a website that displays lines off a script for actors to learn. The problem is that the scriptlet tags are running regardless of the functions. My first thought was to put the whole function inside scriptlet tags, but unfortunately that means that I cant use the variables from the frontend ejs file like textBox and prompt inside those tags because that runs in the server side.
I don't have a lot of knowledge about this so I'm sure I'm wrong on something here. Any tips?
Right now I loop through my RoR objects and create a new jquery function for each separate object. I understand this is extremely inefficient and amateurish, and I would like to have just one jquery function that handles this operation.
<% #startups.each do |startup| %>
<div class="panel-body showVideo<%=startup.id%>">
...
</div>
<div class="panel-body theVideo<%=startup.id%>">
...
</div>
<script type="text/javascript">
$(function () {
$('.theVideo<%=startup.id%>').hide();
$('.showVideo<%=startup.id%>').on('click', function () {
$('.theVideo<%=startup.id%>').show();
$('.showVideo<%=startup.id%>').hide();
});
});
</script>
<% end %>
Basically this code waits for a user to click the div, and hides that div while showing another div. The code currently works, but I don't want to create tons of functions when it could be one!
I think you just need to give the JS access to your IDs. You could do that by writing them into your HTML like this:
<script type="text/javascript">
// Write the IDs into the script tag
var ids = [ <% #startups.each do |startup| %>
<%=startup.id%>,
<% end %>];
// Loop over the IDs
for (var i=0; i<ids.length; i++) {
var id = ids[i];
// Do your stuff here
}
</script>
Of course add some logic to make sure not to add a comma to the last one.
When i call my function in my js.erb template it replaces the entire page rather than just the div that i indicate. Can anyone help?
remove.js.erb
$('div.mini-basket-wrapper').html("<%= j(render 'shop/baskorder/mini_basket') %>");
#This replaces the page completely
$('#basket-info').load(document.write(basket_text()));
view
<div id="basket-info">
<div id="basket-amount">
<div class='mini-basket-icon'>
<%= image_tag 'shop/icons/basket.svg', alt: '' %>
</div>
<script type='text/javascript'>
document.write(basket_text());
</script>
</div>
</div>
JS
function fc_basket_text_from_cookie(empty_text, normal_text)
{
var basket = readCookie('bk');
if (basket)
{
var parts = decodeURIComponent(basket.replace(/\+/g, '%20')).split('|')
if (parseInt(parts[1]) == 0)
return normal_text.replace(/##VALUE##/g, parts[0]).replace(/##ITEMS##/g, parseInt(parts[1]));
// return empty_text
else
return normal_text.replace(/##VALUE##/g, parts[0]).replace(/##ITEMS##/g, parseInt(parts[1]));
} else {
return '';
}
}
var emptyBasketHTML = "<span class='header_text'>Items in basket: 0 Total: £0.00</span>";
function basket_text(){
var populated = "<span class='header_text'>Items in basket: ##ITEMS##</span><span class='header_text'>Total: ##VALUE##</span>";
//populated += "<input type='submit' value='Checkout' name='commit' class='go_botton header-checkout-button'>"
return fc_basket_text_from_cookie(emptyBasketHTML,populated);
}
Reading here: Using document.write.
When the page finishes loading, the document becomes closed. An attempt to document.write in it will cause the contents to be erased.
Further the .load() function is used to load data from a server. I believe you want the .html function.
[Untested] Change the line $('#basket-info').load(document.write(basket_text()));
To $('#basket-info').html(basket_text());
Thanks for all the input. Realised what i was doing wrong and decided to add an ajax on success to my js file:
$(document).on('ajaxSuccess', function(){
$('#basket-amount-info').html(basket_text());
});
Added this id #basket-amount-info to contain the script in the view.
Hey I've faced some curious and unexpected behavior within my .js.erb file. The relevant code and snippets are given for a quick read to help understand the problem.
orders_controller Only partial snippet of the function advanced_search
def advanced_search
#filters = params[:filters] || {}
#is_ajax_search = true
if #filters.present?
response = RestClient.post "my_url/orders/" +#filters.to_json
#orders = JSON.parse response.body
logger.debug [params[:offset], params[:limit], #orders["total"]]
limit = params[:limit] = 50
#orders["order_items"] = #orders["order_items"].paginate(
:page => params[:page],
:per_page => limit,
:total_entries=>#orders["total"]
)
#title = "Advanced Search"
render
end
end
orders/advanced_search.html.erb
<%# debug #orders %>
<% content_for :head do %>
<%= javascript_include_tag 'advanced_search_oms', %>
<% end %>
<%= render "advanced_search_orders_form" %>
<div id="advanced_search_orders_table" class="fk-table ajax">
<%= render "advanced_search_orders_table" %>
</div>
orders/_advanced_search_orders_table
<%= will_paginate #orders["order_items"] %>
javascripts/advanced_search_oms
$(function () {
$('.pagination a').click(function () {
alert("The url will no longer change")
return false;
});
});
But I actually want to define this function in advanced_search.js.erb, as I need to use instance variables.
orders/advanced_search.js.erb
alert("Hello") //Works when a page link is clicked using the will paginate. But is not displayed when the page is loaded. I wonder why?
$(function () {
alert("Dom is loaded") //Woks like previous alert. Only on page click.
$('.pagination a').click(function () {
alert("The url shouldn't change") //But it does. NO ALERT BOX even pops up. It's as if the function doesn't exist.
<%= logger.info "Entered js" %> //But this worked
return false;
});
});
Can you help me understand why this happens, and how should I re-define this function?
I'm trying to assign a javascript variable data from ror. I already made the query, and it gives me what i want (a single integer), but i can't assign it to a js variable. Here is the js script i'm using:
<script type="text/javascript">
$(function() {
var number_of_products = '<%= Post.where(:id => 1).select(:amount).pluck(:amount)[0] %>';
$(document).ready(function(){
for (i=1; i <=number_of_products; i++) $('#itemsAmount').append('<img src="images/box.svg"/>');
})
})
</script>
But i can't seem to pass the ror value (<%= Post.where(:id => 1).select(:amount).pluck(:amount)[0] %>) to the js variable (number_of_products)
Any ideas?
Thanks,
Shai.
It would seem your problem isn't with getting the value into javascript, its simply the wrong type try and change your code to the following
<script type="text/javascript">
$(function() {
var number_of_products = <%= Post.where(:id => 1).select(:amount).pluck(:amount)[0] %>;
$(document).ready(function(){
for (i=1; i <=number_of_products; i++) $('#itemsAmount').append('<img src="images/box.svg"/>');
})
})
</script>
Edit:
Do you have #itemsAmount on your page?
Working fiddle http://jsfiddle.net/DeMd2/