How do I retain the value of like count even after refreshing the page in ruby on rails?
<p>
<input type="button" value="Like" id="countButton" />(<span id="displayCount">0</span>)
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function() {
count++;
display.innerHTML = count;
}
</script>
</p>
The above code increments the value of like each time we hit the like button. After refreshing the page the value of count be comes 0. What to do to retain the values of like after refreshing the page?
Web pages are stateless so every time you refresh the page, any values will be lost unless you specifically save them. If you want to save them forever, you will need to create a database table that saves the number of likes. Each time the like button is clicked you will need to save the new value to the d/b.
You will need a database backed model for whatever it is that is being liked. You may want to look at the rails guides, active record and learn about REST and RESTful routing
It all depends on what you want to do with the counter.
If it is user related, you can store the value in the user's session
like this : session[:counter] = 2.
If the counter should be shared between all users, you will have to create a new field in your database to store it.
Related
I am trying to make it so my textbox input saves after being changed even after page refresh. I successfully made it to work but discovered a few problems.
All my other input textbox now also have the same new stored value once I change one.
This is because I had put the id element of all my textbox inputs for this section of my website the same. I just discovered that this is bad so I am trying to find a fix.
However, if I change all the ids uniquely, how do I make them all store their own modified user inputs without having to re-write the same function code for each id textbox?
Here is my code so far:
Event handling:
//store value after changes
function store(){
var nb = this.value;
localStorage.setItem("qty",nb);
}
//local storage to keep values after refresh
function getValue(){
var storeNb = localStorage.getItem("qty");
if(storedText != null){
document.getElementById("qty").value = storedNb;
}
else
document.getElementById("qty").value = 0;
}
Event registering:
document.getElementById("qty").oninput = store; //stores new values to localstorage upon changes
document.getElementById("qty").onload = getValue(); //gets value from localstorage upon page load
HTML (all the inputs are like thus, one per webpage):
<input type="text" id="qty" name="qty" class="small">
I am using javascript to show text on button click. When I click the button, the text appears then disappears in a flash after page reload.
This is the paragraph that contains the text after clicking the button
<p class="lead" id="class"><strong style="color: red; font-size: 15px; display: none;"></strong></p>
This is my button:
<button type="submit" class="btn btn-primary" onclick="myFunction()">Search</button>
This is my script
<script>
function myFunction() {
document.getElementById("class").innerHTML = "Class current balance total";
}
</script>
How can I make the text show and not disappear after page refresh?
PS : I am very new to javascript.
That is because of type="submit"... try <input type="button" ... /> instead.
You cannot do that with this way. That's not how JS works. In order to keep the data back to the state it was, even after refreshing the page, you need to do that with Localstorage.
Localstorage is a concept in JS, while you are displaying the data after the event happen, you are storing the value in your browser's localstorage, so since the value is already stored in browser, you should be able to retrieve that value.
it shud be something like this localstorage.setItem to save the value and localstorage.getItem to access the saved value and display it on your page.
Hope that answers your question!
I do believe that local storage would help with this problem. I have implemented a solution here for you. Local storage allows web applications to store locally within the user's browser. It is different than cookies. What I have done here is stored your text into local storage as a key/value pair. Local storage retrieves it using the "getItem" method. You can see a demo of this code here
The code:
<script>
//an immediately invoked function that checks to see if the text is in local storage already
(function(){
//if the text is in local storage, set the html
if (localStorage.currentTotal){
console.log(localStorage.currentTotal);
document.getElementById('class').innerHTML = localStorage.getItem("currentTotal");
}
})();
//function that gets called for an onclick event
function myFunction() {
// Store in local storage
localStorage.setItem("currentTotal", "Class current balance total");
//set the inner html to what is in local storage
document.getElementById("class").innerHTML = localStorage.getItem("currentTotal");
}
</script>
The form tag is causing a page reload. Remove the form tags and it should work fine.
Try changing display:none to display:block in your script.
function myFunction() {
document.getElementById("class").innerHTML = "Class current balance total";
document.getElementById("class").children.style.display = 'block';
}
issue with input value is on refresh it disappears,localstorage does not work,but you can get it to work,do setItem code,and getItem but have window.onload and inside document.getElementById("demo").innerHTML =localStorage.getItem("peanuts");you see localStorage has stored info but to display you need to retrieve it,f12 to check its stored,also i add if(typeof(Storage) !== etc., to my code when using localStorage
I added a number counter to a website I made. I need to make it so the number count stays at the current number. For example, if the number is at 3 and I click add one then the next person who visits the website should see 4. Right now it resets to zero every time someone different visits the website.
Html
<div class="box">
<input id="qty" value="0" />
<button id="up" onclick="modify_qty(1)">+ one</button>
<div class="mastfoot">
Javascript
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.getElementById('qty').value = new_qty;
return new_qty;
}
What you need to do is use persistent data storage. The variables are created each time the page is created. So each time the variables are overwritten by 0 as they are recreated.
You can use a server side language like PHP to store data in the database or you use write to a file, then retrieve the data using AJAX requests to make it dynamic.
I have the following drop down list which I am able to append new listings to.
<script>
function Add()
{
var x = document.getElementById("MySelectMenu");
var opt = document.createElement("option");
opt.value= document.getElementById("url").value;
opt.innerHTML = document.getElementById("name").value; // whatever property it has
x.add(opt);
} </script>
<select id="MySelectMenu">
</select>
<button onClick="newSrc();">Load</button>
Name: <input type="text" name="name" id="name">
URL: <input type="url" name="url" id="url">
<button onclick="Add()">ADD</button>
What currently happens (for obvious reasons) is once the user closes the browser page, the list obviously returns to its previou state. How do I make it so the list remembers the appended items?
You can use cookies to save local data for the user, whenever the user adds an item to the list update the local cookie and when the page loads for the first time after a user comes back use an onLoad event to load the items from the cookie into the list.
this ofcourse will only be saved on the BROWSER level for that user, meaning if the same user opens the page in a difrent browser or on a difrent device these changes will not be saved.
to save info on a global nature you will need server side proccessing.
Since javascript or jQuery are front-end scripting languages, the changes made to a page will not be saved.
You would have to explicitly save the newly added items either in Cookies or Session using the following add-on plugins,
https://github.com/carhartl/jquery-cookie
https://github.com/AlexChittock/JQuery-Session-Plugin
And then handle the newly added elements when the page loads at a later time.
Used a method to create some +1 and -1 buttons on a page. (Like a scoreboard)
jQuery - Increase the value of a counter when a button is clicked
However I'm looking for a way to sync the results so that they don't go back to default after each refresh.
Any ideas?
<span id="output">-99</span>
<button class="button right" id="target" type="button">+</button>
<button class="button right" id="targetminus" type="button">-</button>
$('#target').click(function() {
$('#output').html(function(i, val) { return val*1+1 });
});
$('#targetminus').click(function() {
$('#output').html(function(i, val) { return val*1-1 });
});
You need to store the result in the server, in a database, a local file or whichever place suits you best. What you need to do is:
Client side:
Perform an AJAX request to a URL that will increment or decrement the current value. Don't send the current value, because someone else could have modified it since you've loaded the page.
Block your buttons until the AJAX request finishes.
Refresh the current value with the value received by the server
Unblock the buttons.
Server side:
Increment or decrement your current stored value depending on the request send by the browser. This operation must be transactional.
Send the new, updated value to the browser that made the request.
This is not the place to explain how to perform every step. It would depend on your server, your server technology, or whether you have a database or not. I suggest you to learn more about client-server web applications.
I guess you can create a cookie and then read it when you reload. something like this :
function bakeCookie(score) {
document.cookie = "score =" + score + "; path=/";
}
And you can read it when you load the page and set the value.
function eatCookie() {
var score = document.cookie.replace(/(?:(?:^|.*;\s*)score\s*\=\s*([^;]*).*$)|^.*$/, "$1");;
}
Hope it helps.
I'd personally use cookies, There's a really nice little JQuery plugin for them here:
https://github.com/carhartl/jquery-cookie
Also I'd maybe use data attributes on my buttons and tag them with a css class. This way you can then reuse your function to add subtract anything tagged with this data attribute and you can put in any number in the data-val attribute, e.g. 5, -5, 10, -10 etc.
<button class="button right target" type="button" data-val="1">+</button>
<button class="button right target" type="button" data-val="-1">-</button>
$('.target').click(function() {
var val = $(this).data('val');
var score = $.cookie('Score');
$.cookie('Score', score + val);
$('#output').html($.cookie('Score'));
});