Ok, so I'm new and I'm beating my head against the wall!
First here's my fiddle: http://jsfiddle.net/fiddle_me_this/kN272/30/
And the code to boot:
var myArr = [];
var myStr = "";
var restoreList = [];
$(document).ready(function () {
//source file = https://spreadsheets.google.com/feeds/list/17T3iZRygAry052J4clYoVnBUz1h_2ZttBY1mDBh7ZEs/od6/public/basic?alt=json-in-script&callback=?
if (restoreList.length === 0) {
$(function listPlayers() {
$.getJSON("https://spreadsheets.google.com/feeds/list/17T3iZRygAry052J4clYoVnBUz1h_2ZttBY1mDBh7ZEs/od6/public/values?alt=json-in-script&callback=?",
function (data) {
$.each(data.feed.entry, function (i, entry) {
myStr = entry.gsx$player.$t;
myArr.push(myStr);
});
//store default list data
localStorage.myJSON = JSON.stringify(myArr);
});
});
} else {
$('#header').html('Data Exists');
}
});
restoreList = JSON.parse(localStorage.myJSON);
$('#header').html('Offensive Players');
//just using 10 names for now there's over 200 total
for (var i = 0; i < 10; i++) {
$('#player-list').append('<li class="player"><span class="name">' + restoreList[i] + '</span></li>');
if (i === restoreList.length - 1) {
localStorage.clear();
}
}
$('#player-list').sortable('refresh');
$('#player-list').sortable({
connectWith: "ul"
});
I am unable to take the dynamically created list, pulled from a google doc, to connectWith the corresponding list (in gray).
Any help would be appreciated!!
I wonder if this is what you want or not
http://jsfiddle.net/kN272/31/
$('#player-list , #player-list2').sortable({
connectWith: ".connected"
});
Related
The Function "addItemToCart" is not working for my 2nd HTML file maybe because #place and .bag-btn are used in 1st HTML file and that calls the function on click.
Can someone help please? Thank you.
$(function () {
$("#place").on("click", ".bag-btn", addItemToCart);
});
function addItemToCart() {
console.log("Button Pressed");
var btn = $(this);
var parentDiv = btn.closest(".img-container");
let id = parentDiv.attr("data-id");
console.log(id);
$.get("products.json", function (response) {
for (var i = 0; i < response.length; i++) {
var res = response[i];
if (res._id == id) {
//second page work starts here
$("#tabelBody").append(
`<tr><td>res.title</td><td>res.price</td><td>1</td><td>res.price</td></tr>`
);
//above line will add the clicked product in the cart Table
var totalPrice = totalPrice + res.price;
$("#totalPrice").append("Total Price = " + totalPrice);
}
}
});
}
I created an ejs file that can display the documents in the mongodb db collection into the table, and I added select:option that can filtered the table. for example, select:option of date I choose 05/28/2019 it will only display data with 05/28/2019 date. and I already have a download form that can download the table, However the download button only download the whole data in the table and cannot download the filtered data. My question is if there is a way that once I filtered the data in the table and I click download it will only download the filtered data not the whole table. Please see the sample code here https://jsfiddle.net/indefinite/b63y928L/9/
this is the code that can filter the table
$(document).ready(function () {
$('.filter').change(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
and this is what I followed on how to download the html table to csv file https://codepen.io/malahovks/pen/gLxLWX?editors=1010
I expect that once I select a date it will only download the data in the date that I selected. Thank you!
You can modify the row selector to select only visible rows. var rows = $("table tr:visible");. Since you are already using jquery library, you can use the jquery selector.
function export_table_to_csv(html, filename) {
var csv = [];
//var rows = document.querySelectorAll("table tr:visible");
var rows = $("table tr:visible");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV
download_csv(csv.join("\n"), filename);
}
See the updated fiddle https://jsfiddle.net/165yj7se/
Display only new updates of JSON data, iterated with each value item in its own paragraph tag using jQuery/javascript.
If each item in the array inside the info key already is outputted in its own <p> tag; do not continue the loop but wait until there is a new item.
This is my JSON:
{
"info": [
"Hello world,",
"how are you doin?",
"Its not going to well for me unfortunately."
]
}
With this jQuery script:
function updatelog() {
$.getJSON("/static/_info",
function(data) {
$.each(data, function(key, item) {
var value = "";
var i;
for (i = 0; i < item.length; i++) {
value += item[i];
$("div").add('<p>' + value + '</p>').appendTo(document.body);
}
});
});
}
var interval = window.setInterval(updatelog, 2000);
With this I get all the items but it doesn't stop iterating. I have searched the interwebs so much that my enter key has lost all hope for salvation. I guess this is pretty easy, but I'm a beginner and also not a javascript coder and i'm ready to pull my hair off. Thanks in advance.
You could take text of all p elements and push it to new array and then check if it includes values from your object
var data = JSON.parse('{"info":["Hello world,","how are you doin?","Its not going to well for me unfortunately."]}'),
pText = [];
$('p').each(function() {
pText.push($(this).text());
});
data.info.forEach(function(el) {
if (!pText.includes(el)) {
$('body').append('<p>' + el + '</p>');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello world,</p>
You can generate a hash from every list-item and use it as id in the div elements. Everytime you retrieve the data you check if the corresponding id exists. If it exists then the item is already present in your page so you don't have to append it again.
function updatelog() {
$.getJSON("/static/_info",
function(data) {
$.each(data, function(key, item) {
var i;
for (i = 0; i < item.length; i++) {
var value = item[i];
var hashCode = value.hashCode();
if(!$("body").find("#" + hashCode).length){
$("div")
.attr("id", hashCode)
.add('<p>' + value + '</p>')
.appendTo(document.body);
}
}
});
});
}
var interval = window.setInterval(updatelog, 2000);
You can use this implementation for the hashCode function.
Generate a Hash from string in Javascript/jQuery
String.prototype.hashCode = function() {
var hash = 0, i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
My jQuery checkbox filter works normally:
http://jsfiddle.net/EducateYourself/Lmehmj26/3/
Under checkbox form I want to show the number of results. It is 7 by default.
When I filter the results, it does not show the correct number of displayed results.
Could you please help me to find my mistake?
I commented the lines in my jsfiddle code where I added variable n to achieve the result I want.
$('.category').on('change', function () {
var n; //declare variable n
var category_list = [];
$('#filters :input:checked').each(function () {
var category = $(this).val();
category_list.push(category);
});
if (category_list.length == 0) {
$('.resultblock').show();
} else {
$('.resultblock').hide();
});
$('#count').text(n); // change the results qunatity
}
});
The problem is that you are incrementing n multiple times for a single element if it contains multiple matching tags.
You should only increment n once, at most, for each element:
Updated Example
$('.resultblock').each(function() {
var item = $(this).data('tag'),
itemArray = item.split(' '),
hasTag = false;
for (var i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0) {
hasTag = true;
}
}
if (hasTag) {
$(this).show();
n++; // Only increment n once, at most, for each element.
}
});
Here is a cleaner, simplified version of your code:
Updated Example
$('.category').on('change', function() {
var categoryList = $('#filters :input:checked').map(function() {
return this.value;
}).get();
var count = 0;
$('.resultblock').hide().each(function() {
var itemTagsArray = $(this).data('tag').split(' ');
var hasTag = false;
categoryList.forEach(function(tag) {
if (itemTagsArray.indexOf(tag) > -1) {
hasTag = true;
}
});
if (hasTag) {
$(this).show();
count++;
}
});
$('#count').text(count);
});
You're counting doubles, a very easy fix is to add a check for visibility in your for loop like so
for (i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0 && !$(self).is(":visible")) {
$(self).show();
n=n+1; //increase the value of n if found a result
}
}
As shown in this fiddle, that works
As a sidenote, your numbering breaks when you've selected one or more checkboxes and then deselect all. To prevent this you should change your check if there's been any checkboxes checked to
if (category_list.length == 0) {
$('.resultblock').show();
$('#count').text($('.resultblock').length);
}
On page load, I am randomizing the order of the children divs with this Code:
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
I cannot seem to figure out how to get the posts back in the original order. Here's the demo of my current code http://jsfiddle.net/JsJs2/
Keep original copy like following before calling reorder() function and use that for reorder later.
var orig = $("#team-posts").children();
$("#undo").click(function() {
orderPosts();
});
function orderPosts() {
$("#team-posts").html( orig ) ;
}
Working demo
Full Code
var orig = $("#team-posts").children(); ///caching original
reorder();
$("#undo").click(function(e) {
e.preventDefault();
orderPosts();
});
function reorder() {
var grp = $("#team-posts").children();
var cnt = grp.length;
var temp, x;
for (var i = 0; i < cnt; i++) {
temp = grp[i];
x = Math.floor(Math.random() * cnt);
grp[i] = grp[x];
grp[x] = temp;
}
$(grp).remove();
$("#team-posts").append($(grp));
}
function orderPosts() {
// set original order
$("#team-posts").html(orig);
}
How about an "undo" plugin, assuming it applies?
Just give each item a class with the corresponding order and then get the class name of each div and save it to a variable
$("#team-posts div").each(function() {
var parseIntedClassname = parseInt($(this).attr("class");
arrayName[parseIntedClassname] = $("#team-posts div." + parseIntedClassname).html()
});
You can reorder them from there by saving their html to an array in order
$("#team-posts").html();
for(var i=0;i<arrayName.length;i++){
$("#team-posts").append('<div class="'+i+'">'+arrayName[i]+'</div>');
}
The solution with saving away the original order is probably the best but if you have to dynamically sort it, you can use this:
http://www.w3schools.com/jsref/jsref_sort.asp
function orderPosts() {
var $grp = $("#team-posts"),
ordered = $grp.children().toArray().sort(function(a, b) {
return parseInt($(a).text()) > parseInt($(b).text());
});
$grp.empty().append(ordered);
}