I'm a first time poster and I'm learning jQuery, so I'll try to formulate my words as best as possible.
On my site I have multiple pages that dynamically add up the lis and gives me a number.
That number is displayed this way: var totalOverallString = $("#overallTotal").html(total);
Currently I have two similar variables in two functions.
Everything is working correctly on the individual pages.
Now I want to take those two numbers, add them, and display that new number in my home page.
I want this to work dynamically like in my other pages.
The problem I run into is getting those numbers from the other pages.
I've tried .load and .getScript to extract the numbers. I've also tried doing a callback function, but the script loads and gives me the original declared variable: total = 0. This makes sense to me. It's not adding up the lis from the original page. Both variables are global.
I'm trying my best to wrap my head around how to do this. How do I get that dynamically added .html(total) from the other page?
Thanks for your time!
This is the only way I can think to do it without storing all the list items in a database or similar.
Example page 1 containing some list items, here called list-1.html:
<html>
<body>
<ul>
<li>One</li>
<li>Two</li>
</ul>
</body>
</html>
Example page 2 containing some list items, here called list-2.html:
<html>
<body>
<ul>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</body>
</html>
Example page where you want the count of list items to be displayed, in this case, your homepage:
<html>
<body>
<!-- Element to contain the total -->
<p>Total list items: <span id="count">counting...</span></p>
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
(function() {
// Update this array of URLs to the pages containing <li>s that you want to count.
var urls = ["list-one.html", "list-two.html"];
var $hidden = $("<ul />").hide();
var total = 0;
// use jQuery's selective loading functionality to load LIs from each URL, count them, and add the count to a running total
for(var i = 0; i < urls.length; i++) {
$hidden.load(urls[i] + " li", function(responseText) {
total = total + $hidden.find("li").length;
// complete - update the count element.
if(i == urls.length) {
$("#count").html(total);
}
});
}
})();
</script>
</body>
</html>
So essentially we are requesting each page containing list items to count, counting all list items on those pages and keeping a running total.
N.B. depending on the number of pages and lists you need to count, this may not be particularly efficient. But it will work, and I think is the only realistic way you can achieve this without using a DB or complex scraping/caching systems.
you can store your individual values into localStorage or sessionStorage which availlbe with HTML5
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
you can use localStorage or sessionStorage is client side cookies to store your individual value, then you are going to show your total into different page retrieve the value from localStorage and show it :)
Again if you dont want to cache total values set expire time of localStorage 0 which will be expired when browser closed.
for more details on localStorage http://www.w3schools.com/html/html5_webstorage.asp
Related
I'm trying to add a comments from user, so I just tried to read the input and send it to print it , but the problem is that the printed input disappears as soon as I refresh the page or enter another input.
so I want to keep all user's appearing always even when refreshing the page or re-entering a new comment.
code :
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="go()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<script>
function go(){
var x = document.getElementById("UserComment").value;
document.getElementById("t").innerHTML = x;
}
</script>
There are two ways to do this depending on what your use case is.
The first is to use localstorage, which is significantly easier than using a database but has some downsides. Localstorage could be used if the comments were personal (meaning nobody else sees them). The problem with this is that localstorage is insecure.
Localstorage is a set key/value pairs stored on the users machine until deleted.
This is how you use localstorage:
// Place something in localstorage:
window.localStorage.setItem('key', 'value')
//Get something from localstorage:
window.localStorage.getItem('key')
//Delete item from localstorage
window.localstorage.removeItem('key')
Your full application might look something like this:
Javascript:
document.getElementById('comment').innerHTML = window.localStorage.getItem('comment') || ''
HTML:
<!DOCTYPE html>
<html>
<head>
<title>*title here*</title>
</head>
<body>
<textarea placeholder="Type comment here" id="comment"></textarea>
<br/>
<button onmouseup="window.localStorage.setItem('comment',document.getElementById('comment').value)">Submit</button>
</body>
</html>
The second way to do this is to use a database.
There are many different ways to do this, but I would recommend using node.js + express for middleware and mongodb for your database.
Here are some links to get you started:
node.js
npm
express
mongodb
Let me know if I missed anything and/or misunderstood the question.
I think I have a solution that should work for you. I have renamed and refactored some of your code a little, feel free to change it back to the original version if you wish. For me, this was easier to read. I also put the JS in a separate file, but you could accomplish the same task using the script tag.
Here is a link to a JSFiddle that shows it in action JSFiddle User-Comments-App. The code in the fiddle has been modified to work on that site, don't pay attention to it, look at the example below! You can't do page refreshes on JSFiddle so I simulated it with a Refresh Page button and a little timer function that clears the list then repopulates it from local storage.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<!-- calls this function on refresh to pull any coments from local storage -->
<body onload="populateUL()">
<div>
<input type="text" name="comments" placeholder = "Your comment goes here .. " class = "sug-box" id = "UserComment">
<button class = "send-box" onclick="parseUserComment()">Add</button><i class="fa fa-send-o"></i>
<p id = "t"></p>
</div>
<div id="comment-container">
<ul>
<!-- <li> items will be inserted here -->
</ul>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
JavaScript
var commentUL = document.getElementById('comment-container').firstElementChild;
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// we need to reset the counter to begin in the last element of the array when we refresh the page.
commentNumber = localStorage.length;
}
}
Here's a brief breakdown of what's going on, let me know if you have any questions or if something is unclear.
Code Explanation
When the user clicks the 'Add' button, the parseUserComment() function will run. This function takes care of storing the comment in local storage, and displaying the comment on the screen. You'll notice that we pass the work of displaying the comment and storing the comment on to helper functions storeUserComment() and displayUserComment(). The only thing that parseUserComment() actually does is get the user's comment and increment the counter commentNumber:
var commentNumber = 0;
function parseUserComment() {
var userComment = document.getElementById("UserComment").value;
storeUserComment(userComment, commentNumber);
displayUserComment(userComment);
commentNumber++;
}
So, we have the user's comment, and we pass along the userComment to the helper function storeUserComment, which is just a single function call that add's the comment to local storage, using a naming convention 'comment-{commentNumber}'. This would mean the first comment would be 'comment-0', the second 'comment-1'. We use the 0-based system like in arrays. Note the use of template literals to allow us to easily concatenate the commentNumber to the string:
function storeUserComment(userComment, commentNumber) {
window.localStorage.setItem(`comment-${commentNumber}`, userComment);
}
After we have stored the user comment, we want to display it. And this function will also be used to display the user comments on a page refresh. We simply create a new 'li' element, and then make that elements text content the userComment. We then add this element to the 'ul' that sit's inside the div.comment-container, which we selected at the beginning of the file, using the appendChild() method:
// at beginning of file
var commentUL = document.getElementById('comment-container').firstElementChild;
function displayUserComment(userComment) {
var li = document.createElement('li');
li.textContent = userComment;
commentUL.appendChild(li);
}
So that covers the parseUserComment() function and the helpers it calls. Next we need to see how to show the user's comments when the page refreshes. For this, we add an event listener to the 'body' element for the 'onload' event:
<body onload="populateUL()">
The populateUL() function will check to see if there are any items in local storage, and if so, it will loop through those items and call the displayUserComment() function for each item:
function populateUL() {
if (window.localStorage.length > 0) {
var i;
for (i = 0; i < localStorage.length; i++) {
var userComment = window.localStorage.getItem(`comment-${i}`);
displayUserComment(userComment);
}
// bottom of function left off for clarity
At the end of the function, we have to be sure to set the commentNumber to the length of the localStorage array, which would be the last element. So, if you had two comments in localStorage, you would have 'comment-0' and 'comment-1'. The length of localStorage would be 2. We would print out 'comment-0' and 'comment-1' in the loop, then the 'i' variable would increment to 2, and the loop would stop. At this point, we can assign the length of localStorage to the commentNumber, so that if the user wanted to add a new comment, it would start numbering at 2 ('comment-2'):
commentNumber = localStorage.length;
I have made a simple to-do list. But I want to make a list element have a text-decoration = line-through
When I click the button, the list item will be styled with a line-through and it will remain line-through even when I refresh the page or come back to it in a new request (I think local storage is needed).
I thought I could add a class with javascript but I couldn't find how I can do that with local storage.
Below is what I have tried:
HTML:
<ul id="a2">
<li>Make a ramen</li>
</ul>
<button type="button" id="ka" onclick="laylay()" class="" name="button">A</button>
CSS:
.done {
text-decoration: line-through;
}
JS:
function laylay() {
var as = document.getElementById("a2");
as.classList.add("done");
}
If you want to store the state of the list across session or requests and you have no backend storage for the list (meaning it is all stored on the client aka via the browser) you will need to use local storage.
Try this.
localStorage.setItem('a2', 'done');
Then when the page loads get the item from local storage and set the needed class.
localStorage.getItem('a2');
You will need to have an event that fires as soon as the document is ready that will look into your local storage and see if it finds the record it needs and if it does it updates the CSS style.
window.onload(function() {
var itemStyle = localStorage.getItem('a2');
var as = document.getElementById("a2");
as.classList.add(itemStyle);
}
This is not a very scalable solution but for your learning and simple example, it will work.
Try taking the HTML of the element, document.querySelector("#a2").innerHTML;, and saving it as a string in localStorage. And when you need to load it again, try checking if it exists in localStorage, then the string will be set as the innerHTML of #a2
You should have array of object stored in localstorage that look like something this:
[
{todo:'Do something', complete:false},
{todo:'Do something', complete:false},
]
Then when you render todos to page you make conditions based on object what styling your todo should have.
Eg.
let todos=localStorage.getItem('todos');
todos.map(item=>{
if(item.complete){
//code to add this item to page and put .style.textDecoration='line-trough'
}
else{
//code to put item to page
}
})
in order to store this kind of object you will need to stringify it when u set it and than when u use it u need to parse it.You can google it out how to do it.
If you are using some framework it will be much easier to render it on page the way you want, but it can be done with js it is just longer code.
Eg.
//Way to get items from localStorage
let todos=JSON.parse(localStorage.getItem("todos") || "[]");
//Way to set item
localStorage.setItem("todos",JSON.stringify(todos));
Trying to make a dynamic div but i don't know how. Wrote a solidity smart contract that accepts an array of struct. In the smart contract i can use a get function to display the data inside. Data in the array is treated like a history, it consists of amount (making a crowdfund site), date, currency used, etc. Since the get function in the smart contract can only extract one part of the array, i thought of putting the get function into the while loop and extract the whole history array..
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
I'm trying to dynamically create another div with the same amount of < a > in the div. If i had 10 sets of data to display in that div, i wish to create only 10 sets of that div. Can createElement() be used to do that? Couldn't find any solution that works. Totally have no idea on how to create it. Can someone please help.
Would it be rational to extract the data from the array using a while loop and putting it in a div to display or would it use too much gas for this to work?
I don't get why would you want to do this, but you can do like this:
$('#set a').each(function(){
$('#set').after( "<div></div>");
});
It selects all of the <a>...</a> inside the <div id="set">...</div> element, and for each one of those inserts a <div></div> element. It inserts the element right next to #set but you can change that to any other element you could select.
I'm supplying jQuery code since you tagged the question as jQuery.
Hope it helps,
You can get the number of anchor tags by using this function getElementsByTagName('a').length from the hosting div. Then use that number to create new divs. This solution is done using vanilla JS.
function createDynamicDivs(){
var newDiv = document.createElement("div");
var noOfAnchors = document.getElementById('set').getElementsByTagName('a').length;
for(var i=0;i<noOfAnchors;i++){
var newContent = document.createElement("a");
newContent.textContent= "Test ";
newDiv.appendChild(newContent);
}
document.getElementById('new').appendChild(newDiv);
}
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
<div id="new"></div>
<button onclick="createDynamicDivs()">Generate</button>
I have an asp.net 4.5 (C#) page on VS2013. In this page, I am using a loop to itrate threw some of my objects. for each object(product) I have a textbox (input with type=textbox) which I use jquery on to make it a spinner .
I need this inside the loop for every product since I want each spinner to have it's parameters from the object (min, max, step size, is decimal etc.).
The loop goes something like that:
foreach ( Product product in getCart().ItemsList() ) {
String spinnerId = "spinner_" + product.Code;%>
<input id="<%:spinnerId %>" name="<%:product.Code%>">
<script type="text/javascript" language="javascript">
setSpinner('<%:spinnerId%>','<%:product.min%>','<%:product.max%>','<%product.step%>');
</script>
<%}%>
and in the head of the page I have:
function setSpinner(id,minVal,maxVal,stepVal){
j("#"+id).spinner({
min: minVal,
max: maxVal,
step: stepVal,
});
}
The problem is, that when I have the loop goes over a few times (10-15) the page loads very purley and the "onready" functions are taking a few seconds to perform, which meaning some fields that needs to be hidden are shown for 2 seconds and only than disaperas (this includes ajaxcontroltoolkit controls such as popupextender panel etc.).
To make this simple, the javascript code itself makes no matter.
If you try something like this:
<%for (int i=0;i<100;i++){%>
<script type="text/javascript" lang="javascript">
</script>
<%}%>
The same problem occures.
It seemes that even an empty javascript block is making the page take a long time to complete, if youe use it multiple times.
Why are 50\100 empty javascript blocks making the page lag so bad? and what can I do to solve this, considering I have to use the javascript code with each of the my objects data?
Try adding the info you need in data- HTML attributes, and calling javascript one single time. Something like
foreach ( Product product in getCart().ItemsList() ) {
String spinnerId = "spinner_" + product.Code;%>
<input id="<%:spinnerId %>" class="spinner" name="<%:product.Code%>" data-min="<%:product.min%>" data-max="<%:product.max%>" data-step="<%:product.step%>">
<%}%>
Then iterate on the "spinner" class inputs with jQuery:
$("input.spinner").each(function(intput){
$(this).spinner({
min: $(this).data('min'),
max: $(this).data('max'),
step: $(this).data('step'),
});
});
look at #David's ans first that surely is a better approach
as cleared by #roland this is ugly.
even if you need to inject js into the web page. inject a js object preferably and array containing all the objects and then inside a single block on page load iterate through it and get your work done.
var ps = getCart().ItemsList().Select(p=>new {
p.Id
/...All your propertiese.../
});
now inject ps inside the web page / script tag using any json library like Newtonsoft.Json.
var jsonString = JsonConvert.SerializeObject(ps);
Is there a way to use gdata api to retrieve the list of all labels in a blogger?
I need to create a menu based on that list, but cannot simply list all posts and get it, because it is a busy blog and has more than 2000 posts.
Here is the most easy way to get a list of labels by using json call:
<script>
function cat(json){ //get categories of blog & sort them
var label = json.feed.category;
var lst=[];
for (i=0; i<label.length; i++){
lst[i] = label[i].term ;
}
alert(lst.sort()); //use any sort if you need that
}
</script>
<script src="http://yourblog.blogspot.com/feeds/posts/summary?alt=json&max-results=0&callback=cat"></script>
Just use your blog url.
Very simple, I give you two ways
With Javascript API
First, you must use:
<script type="text/javascript" src="http://www.google.com/jsapi"></ script>
<script type='text/javascript'>
google.load("gdata", "1.x", { packages : ["blogger"] });
</script>
Second, you can use the code below to retrieve the labels
postRoot.entry.getCategories()[i].getTerm()
For more tutorials, you can read from http://www.threelas.com/2012/05/how-to-retrieve-posts-using-blogger.html and http://www.threelas.com/2012/04/basic-blogger-javascript-api.html
With JSON
with json, if you want to learn how to retrieve the list of labels, use this object
json.feed.entry[i].category[j].term
for more detail tutorials, read from http://www.threelas.com/2012/02/basic-blogger-json-feed-api.html and http://www.threelas.com/2012/09/blogger-json-feed-with-jquery-ajax.html
The way I found was using the Blogger's own gadget called Labels. It prints the list of labels and their usage count within some unordered lists(ul) and links(a). You can pull the labels from that after they are loaded using javascript as follows:
$(".list-label-widget-content a").each(function (i, el) {
var labelText = $(el).text();
// do what you want with the labels
});
in the end, remove the Labels div element (<div class='widget Label' id='Label1'>)
Widget to server the same purpose is provided by bloggers itself.
Widget provides various options like -
You can either show all Labels or choose from your existing List
You can sort the Labels alphabetically or by number of times that label is used (frequency).
You can choose to display these as a List or as a cloud (jumbled).
You can see the same in my blog - Link
I don't see a method to get the list of labels in a blog, but you can retrieve all posts (https://developers.google.com/blogger/docs/2.0/json/reference/posts/list) and check the labels field for each of them: https://developers.google.com/blogger/docs/2.0/json/reference/posts#resource
First add the JQuery through the following code in console.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();
Once you are done with this we can take advantage of the JQuery and get the list of labels
Now what I am doing will work for the Blogger Theme Notable and newly added Theme for blogger.
Normally in these themes you will see Labels in the rights side toogle menu of the page.
So What you need it Click on the Label and Click on Show more.
Now Open Browser Debugging console and declare and variable.
var str = "";
Now run the two codes below
1. $('.first-items .label-name').each(function(){str = str + ", "+($(this).text())})
2. $('.remaining-items .label-name').each(function(){str = str + ", "+($(this).text())})
3. str
all the labels you will be get in comma(;) separated format.