I'm using the jquery plugin called shapeshift. It's like jqueryui sortable but with better animations. The divs can be dragged and dropped. But I can't seem to figure out how to save their order so that on browser refesh the order remains the same where I left them.
Here is the jsfiddle http://jsfiddle.net/Shikhar_Srivastava/aC367/
$(".container").shapeshift({minColumns: 3});
I'm initiating the plugin as above.
Please help me on my fiddle.
Thanks.
I would create a cookie. So I would first include the jQuery Cookie script (found here: https://github.com/carhartl/jquery-cookie/blob/master/src/jquery.cookie.js), then create the cookies (one for each each .container) each time an element is moved:
/* save cookie */
$('.container').on("ss-drop-complete", function() {
var containerCookieCounter = 0;
$('.container').each(function() {
/* cookie = 12h */
var date = new Date();
date.setTime(date.getTime() + (720 * 60 * 1000));
$.cookie('savepositions' + containerCookieCounter, $(this).html(), { expires: date, path: '/' });
containerCookieCounter += 1;
});
});
Then, before initiating the shapeshift-function, check if there are existing cookies:
/* cookies... */
if ($.cookie('savepositions0')) {
var containerCounter = 0;
$('.container').each(function() {
$(this).html($.cookie('savepositions' + containerCounter));
containerCounter += 1;
});
}
Here is a working fiddle: http://jsfiddle.net/Niffler/FvUcQ/
Only one container
Fiddle
var $con=$(".container").shapeshift({
minColumns: 3
});
function getPos(id){
var p=localStorage[id];
var ro={left:100000,top:-1,unknown:true};
if(p!==undefined) ro=JSON.parse(p);
//alert('get Pos:'+id+' '+JSON.stringify(ro));
return ro;
}
function setPos(id,p){
//alert('set Pos:'+id+' '+JSON.stringify(p));
localStorage[id]=JSON.stringify(p);
}
function arrange(){
var o={};
var con=$(".container:nth-child(1)");
var els=$(".container:nth-child(1) div");
els.each(function(x){
var me=$(this);
var id=me.attr('id');
var o_=o[id]={};
o_.id=me.attr('id');
o_.p=getPos(id);
});
for(var i in o){
var oo=o[i];
var el=$('#'+oo.id);
if(!oo.unknown){
el.css('left',''+oo.p.left+'px');
}
}
}
function savePs(){
var els=$(".container:nth-child(1) div");
els.each(function(){
var me=$(this);
setPos(me.attr('id'),me.position());
});
}
var $con=$(".container:nth-child(1)");
$con.on('ss-rearranged',function(e,selected){
var id=$(selected);
setTimeout(function(){
//var me=$(selected);
savePs();
//setPos(me.attr('id'),me.position());
},500);
});
arrange();
//savePs();
Fiddle
As commenters have suggested, you need to use localStorage to store and retrieve the state, and save that state after the ss-drop-complete event.
Here is the entire JS I used in this updated jsFiddle:
$(function () {
// retrieve from localStorage if there is a saved state
var saved = localStorage.getItem('arrangement');
if (saved) {
populateArrangement($('.container').parent(), JSON.parse(saved));
}
$(".container").shapeshift({
minColumns: 3
}).on('ss-drop-complete', function () {
// get the new arrangement and serialise it to localStorage as a string
var rows = getArrangement();
localStorage.setItem('arrangement', JSON.stringify(rows));
});
// return the data needed to reconstruct the collections as an array of arrays
function getArrangement() {
var rows = [];
$('.container').each(function () {
var elementsInRow = [];
$(this).find('.ss-active-child').each(function () {
elementsInRow.push({
value: parseInt($(this).text(), 10),
colspan: $(this).data('ss-colspan') || 1
});
});
rows.push(elementsInRow);
});
return rows;
}
// use the arrangement to populate the DOM correctly
function populateArrangement(container, newArrangement) {
$(container).find('.container').remove();
$.each(newArrangement, function (index, row) {
var $container = $('<div class="container"></div>');
$container.appendTo(container);
$.each(row, function (index, element) {
var $div = $('<div></div>');
$div.text(element.value);
if (element.colspan > 1)
$div.attr('data-ss-colspan', element.colspan);
$container.append($div);
});
});
}
});
If you have some sort of server side code you can add the order to a hidden field on the ss-drop-complete function and then post this back to the server on post back. You can then just re-output the values back when the page re-renders and you can use this information in any server side code you need.
I've done something similar when working with jquery mobile and ASP.NET to save back to a database the order.
If not, the local storage option could be a good way to go.
Related
I am trying to filter one dropdown from the selection of another in a Rails 4 app with jquery. As of now, I have:
$(document).ready(function(){
$('#task_id').change(function (){
var subtasks = $('#subtask_id').html(); //works
var tasks = $(this).find(:selected).text(); //works
var options = $(subtasks).filter("optgroup[label ='#{task}']").html(); // returns undefined in console.log
if(options != '')
$('#subtask_id').html(options);
else
$('#subtask_id').empty();
});
});
The task list is a regular collection_select and the subtask list is a grouped_collection_select. Both which work as expected. The problem is that even with this code listed above I can't get the correct subtasks to display for the selected task.
NOTE: I also tried var tasks=$(this).find(:selected).val() that return the correct number but the options filtering still didn't work.
Try something like this instead (untested but should work).
$(function () {
var $parent = $('#task_id'),
$child = $('#subtask_id'),
$cloned = $child.clone().css('display', 'none');
function getParentOption() {
return $parent.find('option:selected');
}
function updateChildOptions($options) {
$child.empty();
$child.append($options);
}
$parent.change(function (e) {
var $option = getParentOption();
var label = $option.prop('value'); // could use $option.text() instead for your case
var $options = $cloned.find('optgroup[label="' + label + '"]');
updateChildOptions($options);
});
});
I'm having trouble changing the class after making a jquery get request.
code:
<script>
//global variable
var table = []
var numberofaccounts = 0
$(document).ready(function() {
$('#form1').validate();
// add numbers to select ids
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
$('#apply_btn').click(function() {
table = []
var count = 0;
var text = "";
var tracker = 0
$('#stats_table tr').each(function(){
count = 0;
text = "";
$(this).find('td').each(function(){
count++;
if (count == 4) {
text += $( ".select_class"+ tracker + " option:selected" ).val();
} else {
text += " " + $(this).text() + " ";
}
})
table.push(text);
tracker++;
});
$.post("/apply_changes", {"data": JSON.stringify(table)}, function(data) {
var res = JSON.parse(data);
if (res.data == true){
$('#updated').text("Update Successful").css('color', 'green');
$.get("/", function( data ) {
$('#stats_table').load("/ #stats_table");
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
} else {
$('#updated').text("Update Unsuccessful").css('color', 'red');
}
});
});
});
</script>
So when the page first loads this method changes the class on dynamically created select elements.
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
After I make a post to flask the if the response data is true I go ahead and make a get request to grab the updated items from the db. I then refresh the table. This works great if I make one request. However on the second post nothing happens. This is because the classes that I modified at the start of the page load no longer exist. So i added the method above to also trigger after the get response (I also tried at the end of the post response). The problem is that the method doesn't seem to run again. The classes aren't there and as a result when I go to make another post request it can't find the element. How do I go about fixing this?
Things to note: The get request is necessary, the ids and classes cannot be statically assigned.
You are trying to assign classes before you even refresh your table.
$('#stats_table').load("/ #stats_table"); is called asynchronously and returns before it even completes.
You need to put you code, for assigning classes, inside the complete callback of your .load() call:
$('#stats_table').load("/ #stats_table", function() {
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
I have a function set up with the jQuery cookie plugin: https://github.com/carhartl/jquery-cookie, with the click function on .grid-block it stores each data-hook in an array, saves them as a cookie, then these chosen divs are viewable on the /itin/your-itin/ page. Here's a demo I've set up too: http://nealfletcher.co.uk/itin/ If you click on the .grid-block divs, this will add them to your itinerary, then when you navigate to: http://nealfletcher.co.uk/itin/your-itin/ only these divs are viewable and stored as a cookie for x amount of time. This works great, BUT if I then go back to add more divs, these are stored as a cookie, but the previous ones are wiped, I want to keep appending to the array, store it as a cookie, then when you navigate to: http://nealfletcher.co.uk/itin/your-itin/ it will display all your selections, even if they've been added separately. If that makes sense?
jQuery:
$(window).load(function () {
var cfilter = [];
var $container = $('.block-wrap');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.grid-block',
animationEngine: 'best-available',
filter: '.grid-block',
masonry: {
columnWidth: 151
}
});
$(".grid-block").click(function () {
var thing = $(this).attr("data-hook");
var test = "." + thing;
cfilter.push(test);
$.removeCookie('listfilter', {
path: '/itin/your-itin/'
});
// We need to set the cookie only once
// it stays at the url for 7 days
$.cookie("listfilter", cfilter, {
expires: 365,
path: '/itin/your-itin/'
});
});
if ($.cookie("listfilter") !== 'null') {
// console log just for testing
console.log($.cookie());
$('.block-wrap').isotope({
filter: $.cookie("listfilter")
});
return false;
} else {
// !! this part could be refactored
// as you don't really need to check against the url
// when the cookie doesn't exist show all elements
$('.block-wrap').isotope({
filter: ''
});
}
});
});
Any suggestions would be greatly appreciated!
Change var cfilter = []; to var cfilter = $.cookie("listfilter");
This way you load the changed cookie and add to it instead of overwriting it.
Better code practice would be to check if the cookie exists before using it though, but you get my hint.
You made an error in implementing my change:
if ($.cookie("listfilter") !== 'null') {
var cfilter = [];
} else {
var cfilter = $.cookie("listfilter");
}
is wrong, use
if ($.cookie("listfilter")) {
var cfilter = $.cookie("listfilter");
} else {
var cfilter =[];
}
I'm trying to see how I can fix a problem that I'm having with jQuery Tablesoter widget called 'filter', it stops working after the table is updated without any error message and it does this on all web browsers, the other widgets work like zebra and savesort only filter stops working.
here is the code:
<script type="text/javascript" src="tablesorter/OVOjquery-1.10.2.min.js"></script>
<script type="text/javascript" src="tablesorter/OVOjquery.tablesorter.min.js"></script>
<script type="text/javascript" src="tablesorter/OVOjquery.tablesorter.widgets.min.js"></script>
<script type="text/javascript" src="tablesorter/OVOjquery.tablesorter.pager.min.js"></script>
<script type="text/javascript" src="tablesorter/final/toastmessage/jquery.toastmessage-min.js"></script>
<script type="text/javascript" src="tablesorter/qtip/jquery.qtip.min.js"></script>
<!--//c24-->
<script type="text/javascript">
var comper;
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 2000);
});
}
function updateTable() {
return $.get('updatetableNEW.php', function (data) {
console.log('update table');
var $table = $("table.tablesorter");
var $tableContents = $table.find('tbody')
////// var $html = $('<tbody/>').html(data);
$tableContents.replaceWith('<tbody>' + data + '</tbody>')
//$tableContents.replaceWith($html)
$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$(function(){
var tid = setTimeout(checkComper, 2000);
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
// define pager options
var pagerOptions = {
// target the pager markup - see the HTML block below
container: $(".pager"),
// output string - default is '{page}/{totalPages}'; possible variables: {page}, {totalPages}, {startRow}, {endRow} and {totalRows}
output: '{startRow} - {endRow} / {filteredRows} ({totalRows})',
// if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty
// table row set to a height to compensate; default is false
fixedHeight: true,
// remove rows from the table to speed up the sort of large tables.
// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
removeRows: false,
// go to page selector - select dropdown that sets the current page
cssGoto: '.gotoPage'
};
// Initialize tablesorter
// ***********************
$("table")
.tablesorter({
theme: 'blue',
headerTemplate : '{content} {icon}', // new in v2.7. Needed to add the bootstrap icon!
widthFixed: true,
widgets: ['savesort', 'zebra', 'filter'],
headers: { 8: { sorter: false, filter: false } }
})
// initialize the pager plugin
// ****************************
.tablesorterPager(pagerOptions);
// Delete a row
// *************
$('table').delegate('button.remove', 'click' ,function(){
var t = $('table');
// disabling the pager will restore all table rows
t.trigger('disable.pager');
// remove chosen row
$(this).closest('tr').remove();
// restore pager
t.trigger('enable.pager');
});
// Destroy pager / Restore pager
// **************
$('button:contains(Destroy)').click(function(){
// Exterminate, annhilate, destroy! http://www.youtube.com/watch?v=LOqn8FxuyFs
var $t = $(this);
if (/Destroy/.test( $t.text() )){
$('table').trigger('destroy.pager');
$t.text('Restore Pager');
} else {
$('table').tablesorterPager(pagerOptions);
$t.text('Destroy Pager');
}
return false;
});
// Disable / Enable
// **************
$('.toggle').click(function(){
var mode = /Disable/.test( $(this).text() );
$('table').trigger( (mode ? 'disable' : 'enable') + '.pager');
$(this).text( (mode ? 'Enable' : 'Disable') + 'Pager');
return false;
});
$('table').bind('pagerChange', function(){
// pager automatically enables when table is sorted.
$('.toggle').text('Disable');
});
});
</script>
<!--//c24-->
Maybe the filter widget needs to be reloaded after the table update ?
I first thought that the updated table does not have the correct formatting so I saved the view source as a html file and when I open the page locally the 'filter' (search) works fine, so it cannot be the table (<TD>) formatting or so I think, but what can it be, can anyone please help me I have been trying to get this to work for two weeks now and I'm out of ideas as my knowledge here is limited :( Thanks.
It looks like the plugin needed to know that we made an update and I just needed to trigger the updateAll command.
Like this:
var resort = true, // re-apply the current sort
callback = function(){
// do something after the updateAll method has completed
};
$("table").trigger("updateAll", [ resort, callback ]);
There is a lot of code to wade through, but you might want to try updating the table contents like this:
var $table = $("table.tablesorter");
$table.find('tbody').html(data);
$table.trigger("update", [true]);
I'm only guessing that the replaceWith() function isn't working as intended.
Same problem here.
Short solution: make the filter-select to a filter-match class, then the table will work again.
Long solution: Does anyone have a working example of table sorter combined with ajax pager and filter plugin?
i get this error, and i don't know how can be solved. I read this link before.
EDIT:1
index.php
<script type="text/javascript">
$(document).ready(function() {
$("#customForm").submit(function() {
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data) {
switch (data.livre) {
case 'tags':
$("#msgbox2").fadeTo(200, 0.1, function() {
$(this).html('Empty tags').fadeTo(900, 1);
});
break;
default:
$("#msgbox2").fadeTo(200, 0.1, function() {
$(this).html('Update').fadeTo(900, 1, function() {
$('#conteudo').load('dojo/test_Slider.php');
});
});
break;
}
}
});
return false;
});
});
</script>
test_slider.php
<script type="text/javascript">
var slider = [];
for (i = 0; i < 5; i++) {
slider[i] = (
function(i) {
return function() {
var node = dojo.byId("input"+[i]);
var n = dojo.byId("valores"+[i]);
var rulesNode = document.createElement('div'+[i]);
node.appendChild(rulesNode);
var sliderRules = new dijit.form.HorizontalRule({
count:11,
style:{height:"4px"}
},rulesNode);
var labels = new dijit.form.HorizontalRuleLabels({
style:{height:"1em",fontSize:"75%"},
},n);
var theSlider = new dijit.form.HorizontalSlider({
value:5,
onChange: function(){
console.log(arguments);
},
name:"input"+[i],
onChange:function(val){ dojo.byId('value'+[i]).value = dojo.number.format(1/val,{places:4})},
style:{height:"165px"},
minimum:1,
maximum:9,
}
},node);
theSlider.startup();
sliderRules.startup();
}
})(i);
dojo.addOnLoad(slider[i]);
}
</script>
Problem: First click in submit btn all works well, 5 sliders are imported. Second click, an update is supposed, but i get this message:
Tried to register widget with id==valores0 but that id is already registered
[Demo video]2
Just to add on to #missingo's answer and #Kevin's comment. You could walk through the existing dijits by looking in the registry:
var i = i || 0; // Cache this at the end of your loop
dijit.registry.map(function (widget) {
if (+widget.id.replace(/^[^\d]+/, '') < i) {
widget.destroyRecursive();
}
});
/*
Your loop fixed as described in missingno's answer.
*/
You fell in the age-old trap of making function closures inside a for loop. By the time addOnLoad fires and the sliders are created, i will be equal to 2 and both sliders will try to use the same DOM nodes (something that is not allowed).
You need to make sure that you give a fresh copy of i for everyone. The following is a quick fix:
for(i=0; i<2; i++){
(function(i){
slider[i] = ...
//everything inside here remains the same
//except that they now use their own i from the wrapper function
//instead of sharing the i from outside.
}(i));
}
Dijit stores all active widgets in the dijit.registry, and uses id's as unique qualifiers. You can't create dijits with same id.
Need to clean dojo.registry before create a new slider dijits. Add this code before declare dijit on test_slider.php
dijit.registry["input"+ [i]].destroyRecursive();
can you assign any number ID like ID generated by 10 digit random number or something with datetime combination so id will never be same.