Jquery - Syncing results of incremental counters that increase/decrease on click - javascript

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'));
});

Related

Text shows then disappears on page reload; javascript onclick event

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

change php value with javascript

)
I work for pagination for my table, my problem is where I click "next" the javascript increase ( I show it with alert) and not php value, so I think the my page is not refresh
get php value :
<input type="hidden" name="page" value="<?=$this->page?>" id="page">
button next :
<li class="page-item" ><a class="page-link" id="page_sui" href="#" >Next</a></li>
javascript:
$("#page_sui").click(function{
var val = $("#page").val();
val++;
$("#page").val(val);
alert($("#page").val());
});
PHP values cannot be changed through Javascript. When you click your button you are calling a Javascript function, and Javascript functions can only change Javascript variables and DOM elements. If you want to navigate to the next page with your current code, change your Javascript to this:
$("#page_sui").click(function{
var val = $("#page").val();
val++;
$("#page").val(val);
window.location='mypage.php?page=' + val;
});
And then in your PHP file add this:
if (!empty($_GET['page'])) $this->page = intval($_GET['page']);
Lastly, do NOT use <?=, it's bad practice!
Your script is not communicating the request from the browser to the server. By writing value="<?=$this->page?>", the server code (php) is putting the value in the HTML for the browser (javascript) to interpret and use. By writing $("#page").val(val);, only the value in the browser is changing but it does not send this request to the server to get more data. To do this you need to either navigate to a URL using window.location from javascript, or use AJAX from javascript to load the content you want and then place it on the page using javascript.

Retain the values after refeshing the page

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.

How to make a number counter stay at current number for anyone visiting site

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.

Disable AJAX button after nth click

Given I have a model Post which can have up to n Comments (the number is controlled by the Backend) and I have a view which allows to add a Comment via a AJAX request. What is the best way to tell the view upon the nth request to disable the Add-Comment-Form?
The nth request is successfull so status code should still be 200/201 but the backend already "knows" that the nth + 1 call will invalidate the Post, so i want to somehow tell this to the view so it can take action before the user experiences the (catched) error upon nth + 1 submit.
By now the backend renders html which is then simply attached to a div in the DOM, with JSON I might add an additional field but then would move the templating to the view again.
If someone has an idea for an elegant solution?
Try having your server render javascript value for comment count and max comments. Then you can increment the count value in your success function as well as perhaps render the html comment.
Something like
var commentCount = *value from server*;
var maxComments =*value from server*;
$('#mybutton').click(function(){
$.ajax({
// your code here
})
. success(function (response) {
// process response
commentCount ++;
if( commentCount >= maxComments)
$('#mybutton). prop('disabled', true);
});
Just hide the "Add comment" button by JavaScript, when it will be "nth + 1". Or remove eventListener from button and change caption to smth like "You reached max comments".
Keep a track of the number of clicks. After the n th click, you can change the disabled attribute of your button to true.
$(".myButton").attr("disabled",true);

Categories