Display 'sum' on another page - javascript

I am currently having a problem displaying a calculated sum on the next page in javascript/html.
My calculation for defining the sum looks like this, where the 'sum + €' is displayed at the end.
function udregnPant() {
let sum = 0;
for (i = 0; i <= pantListParsed.length; i++) {
let totalPantKr = pantListParsed[i].aPantMoney + pantListParsed[i].bPantMoney + pantListParsed[i].cPantMoney;
sum += totalPantKr;
console.log(sum);
document.getElementById('sumAfPantB').innerHTML = sum + " €.";
}
}
In the following HTML input I want to display the sum as the value instead of '10 €'
<input type="text" name="amount" id="text1" value="10 €." readonly/>
Appreciate your help!

Make use of web storage.
sessionStorage - stores data for one session
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
localStorage - stores data with no expiration date
localStorage.getItem('label')
localStorage.setItem('label', 'value')
Example
function setSum(value) {
localStorage.setItem("sum", value);
}
function getSum() {
return localStorage.getItem("sum");
}
Live Example at JS Bin
References
Share data between html pages
HTML5 Web Storage

After calculating your value, redirect the user to a URL with the value in the query string (See Redirections in HTTP) -- this may look something like
window.location = http://mysite/page2.html?amount=12
On the new page, retrieve the value from the query string using the searchParams property (see URL.searchParams). Could look something like:
let params = (new URL(document.location)).searchParams;
document.getByElementId('text1').value = params.get('amount');

Here is a little example using local Storage, since so doesnt allow local storage try it in jsfiddle and
the code sample as well:
document.getElementById('btnSend').onclick = ()=>{
let total = document.getElementById('txtTotal').value;
if(!isNaN(total) && total > 0){
localStorage.setItem('total', total);
document.getElementById('txtTotal').value = '';
}
}
document.getElementById('btnLastTotal').onclick = ()=>{
var lastTotal = localStorage.getItem('total');
if(lastTotal !=undefined){
alert('last total is:'+lastTotal);
}else{
alert('No records found');
}
}
<input type="text" id="txtTotal">
<br>
<input type="button" id="btnSend" value="Save the total"> <input type="button" id="btnLastTotal" value="get Last Total">
Hope it helps

Related

Subtract amount on form submit JavaScript / JQuery

I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.
Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.
The function I have should have these features:
create form
get input value
subtract used points from user's total amount (for example totalPts = 1000)
subtract from cart total value used points, converted into $ (100pts = 1$)
For now, my function looks like this:
function appendRefferalPoints() {
const totalPts = 1000;
// creating form - ok
$form = $('<form id="refForm" class="coupon-form" action></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
);
$form.append('<button type="submit" class="btn">Aplica</button>');
$("body").append($form);
// get input value - not ok
$("#refForm").submit(function () {
let value = 0;
$.each($("#refForm").serializeArray(), function (i, field) {
value[field.name] = field.value;
});
});
// subtraction from totalPts logic - not ok
let rez = totalPts - value;
console.log("Final Rez: " + rez);
// subtraction converted pts from cart value logic
}
Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart
function appendRefferalPoints() {
const totalPts = 1000;
let cartValue=10;
let discount=0;
let inputValue = 0;
// creating form - ok
$form = $('<form id="refForm" class="refForm coupon-form" ></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" value="100" >'
);
$form.append('<button id="btnClick" class="btn">Aplica</button>');
$("body").append($form);
$(document).on("submit", "#refForm", function(e){
//getting input value while submitting form
inputValue=$("#refValue").val();
//converting 100 pts to 1 dallor
discount=inputValue/100;
//calculating balance pts
let balancePts = totalPts - parseInt(inputValue);
//calculating final amount
let finalCartValue=cartValue-discount;
alert("finalCartValue"+finalCartValue);
});
}
appendRefferalPoints();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Data to another page

I’m trying to have an input on one page where, let’s say, the user puts their name in, and then on clicking the submit button it takes them to another page where it says Hello “name”.
I seem to have it working, but then when I tried another page it doesn't carry the input over.
Is there a way to do this all on one page? I don’t want the output showing. If it's one page I want to make a transition so it's like a full screen input name: then submit transition into a new screen with Hello, “name”.
Code I have so far:
<label>Type your name: </label>
<input type="text" id="txtName">
<input type="button" value="click me" onclick="transfer()">
<script>
function sayHi(){
  var txtName = document.getElementById("txtName");
  var txtOutput = document.getElementById("txtOutput");
  var name = txtName.value;
  txtOutput.value = "Hi there, " + name + "!";
}
function transfer() {
location.href = "output.html";
}
</script>
New page
<input id="txtOutput">
Take a look in the localstorage API. Localstorage allows you to store data in the browser like this:
localStorage.setItem('item1', 'value1');
You can access later like this data later like this:
let cat = localStorage.getItem("item1");
You need to send value in page 1 to Page 2. In your case you are execute script in Page 1 and taking the user to Page 2 where the entire page loads again. Your executed script is gone.
Your Page1.html
<label>Type your name: </label>
<input type="text" id="txtName">
<input type="button" value="click me" onclick="transfer()">
<script>
function transfer() {
location.href = "output.html?name="+document.getElementById("txtName").value;
}
</script>
Now, your user will be taken to output.html?name={name he had entered}
output.html:
<input id="txtOutput">
<script>
// function to get data from URL.
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
document.getElementById("txtOutput").value = "Hi "+findGetParameter("name");
</script>
Please let me know if it was helpful. However, I would suggest you to understand how back_end technologies work. and look at local storage.

Store values from dynamically generated text boxes into array

I'm creating a Time table generating website as a part of my project and I am stuck at one point.
Using for loop, I am generating user selected text boxes for subjects and faculties. Now the problem is that I cannot get the values of those dynamically generated text boxes. I want to get the values and store it into array so that I can then later on store it to database
If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.
Following is my Jquery code
$.fn.CreateDynamicTextBoxes = function()
{
$('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');
InputtedValue = $('#SemesterSubjectsSelection').val();
SubjectsNames = [];
for (i = 0; i < InputtedValue; i++)
{
TextBoxContainer1 = $('#DynamicTextBoxContainer');
TextBoxContainer2 = $('#DynamicTextBoxContainer2');
$('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer1);
$('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer2);
SubjectsNames['SubjectTextBoxes'+i];
}
$('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
}
$.fn.CreateTimeTable = function()
{
for (x = 0; x < i; x++)
{
localStorage.setItem("Main"+x, +SubjectsNames[i]);
}
}
I am also posting screenshot for better understanding
I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.
First of all, I think you should create single plugin instead of two, and expose what you need from the plugin.
You should avoid global variables, right now you have InputtedValue, i, SubjectsNames, etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need.
You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it.
Take a look at the snippet I created. I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. I pass some selectors as in configuration object to make it more reusable. I added 2 buttons to make it more "playable", but you can change it as you prefer. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (e.g. store them in local storage).
$(function() {
$.fn.timeTables = function(config) {
// prepare variables with jQuery objects, based on selectors provided in config object
var numberOfSubjectsTextBox = $(config.numberOfSubjects);
var subjectsDiv = $(config.subjects);
var facultiesDiv = $(config.faculties);
var prepareButton = $(config.prepareButton);
var numberOfSubjects = 0;
prepareButton.click(function() {
// read number of subjects from the textbox - some validation should be added here
numberOfSubjects = +numberOfSubjectsTextBox.val();
// clear subjects and faculties div from any text boxes there
subjectsDiv.empty();
facultiesDiv.empty();
// create new text boxes for each subject and append them to proper div
// TODO: these inputs could be stored in arrays and used later
for (var i = 0; i < numberOfSubjects; i++) {
$('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv);
$('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv);
}
});
function generate() {
// prepare result array
var result = [];
// get all text boxes from subjects and faculties divs
var subjectTextBoxes = subjectsDiv.find('input');
var facultiesTextBoxes = facultiesDiv.find('input');
// read subject and faculty for each subject - numberOfSubjects variable stores proper value
for (var i = 0; i < numberOfSubjects; i++) {
result.push({
subject: $(subjectTextBoxes[i]).val(),
faculty: $(facultiesTextBoxes[i]).val()
});
}
return result;
}
// expose generate function outside the plugin
return {
generate: generate
};
};
var tt = $('#container').timeTables({
numberOfSubjects: '#numberOfSubjects',
subjects: '#subjects',
faculties: '#faculties',
prepareButton: '#prepare'
});
$('#generate').click(function() {
// generate result and 'print' it to result div
var times = tt.generate();
var result = $('#result');
result.empty();
for (var i = 0; i < times.length; i++) {
$('<div>' + times[i].subject + ': ' + times[i].faculty + '</div>').appendTo(result);
}
});
});
#content div {
float: left;
}
#content div input {
display: block;
}
#footer {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div id="header">
<input type="text" id="numberOfSubjects" placeholder="Number of subjects" />
<button id="prepare">
Prepare
</button>
</div>
<div id="content">
<div id="subjects">
</div>
<div id="faculties">
</div>
</div>
</div>
<div id="footer">
<button id="generate">Generate</button>
<div id="result">
</div>
</div>

localStorage keeps adding '0'. (jScript & HTML5)

Well, my code have been working fine and I'm simply trying to make a simple game, until I added this (due to that I wanted to learn how to save the info to the users local storage):
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
My full code looks like this:
<head><meta charset="UTF-8"></head>
<body><span id='test'></span>
Generated something: <span id='money'>0$</span> (money per click: <span id='MPC'>1$</span>)
<br />
Upgrade 1 upgrades: <span id='u1Us'>0</span> (production rate: <span id='u1Pr'>0</span>)
<br />
<span id='updates'></span>
<br />
<button onClick='mButton()'>Generate something.</button>
<br /><br />
<b>Upgrades:</b>
<br /><br />Generator upgrades:<br />
<button onClick='buyU1()'>Buy upgrade 1. ($30)</button>
<br /><br />Self-generated upgrades:<br />
<button onClick='buySG1()'>Buy Self-Generated Upgrade 1 ($500)</button>
</body>
<script>
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
var U1Amount = 0;
var cMoney = 1;
function mButton()
{
Money += cMoney;
document.getElementById('money').innerHTML=Money + "$";
}
function buyU1()
{
if(Money < 30)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 30;
U1Amount += 1;
document.getElementById('u1Us').innerHTML=U1Amount;
document.getElementById('money').innerHTML=Money + "$";
document.getElementById('updates').innerHTML="You have successfully bought Upgrade 1";
var calcU1Amount = U1Amount * 5;
document.getElementById('u1Pr').innerHTML=calcU1Amount;
resetUpdates();
}
}
var interval = setInterval(gMoneyU1, 1000);
function gMoneyU1()
{
var calc = 5 * U1Amount;
Money += calc;
document.getElementById('money').innerHTML=Money + "$";
}
function buySG1()
{
if(Money < 500)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 500;
cMoney += 1;
document.getElementById('MPC').innerHTML=cMoney + "$";
document.getElementById('money').innerHTML=Money;
}
}
function resetUpdates()
{
setTimeout(function(){document.getElementById('updates').innerHTML="";}, 10000);
}
</script>
I'm going to add the localStorage to all info that I want to save, but I'm having problems with the first one so yer.
What my code WITH my save-the-persons-info outputs is: http://puu.sh/6iONl.png (and it keeps on in all eternally)
It keeps adding '0' for some reason and I can't figure out why. I'd really appreciate help.
Thanks in advance.
Sorry if my code is messy, I'm still learning, hence why asking for help.
The only time that you ever set to localStorage is when you call localStorage.setItem('money', 0);.
You probably want to change that to setting the real value of the money variable.
Local storage stores everything as a string, so you'll want to call parseInt() on whatever you get back from local storage. Then, you should be able to properly add two ints together, rather than concatenating two strings together.
The values in localStorage are all strings. When you do:
localStorage.setItem('x', 0);
var x = localStorage.getItem('x'); // x === '0'
x = x + 1; // x = '01';
the thing you set in local storage will be the value you gave converted to a string. You should parseInt (or convert it some other way back to a number) when you retrieve it from localStorage to avoid this problem.
Your if statement will always return false so you'll never get to the "if true" part of your if statement. This is because the local storage value will either be null if not set, or a string value ("0") on most browsers if set, or an integer on some browsers if set. (Most browsers will only maintain strings for local storage, although the HTML5 specs do allow for other values.)
So first, of you would need to change the if part to something like this:
if (localStorage.getItem('money') != null)
I'm not completely sure what you're trying to achieve logic-wise but as mentioned, your other issue is that you're only setting the value to 0 and then reading the value right after (which would be zero still.) This is why you're getting zeros.

Keeping clicked checkboxes state after page refresh

Users select checkboxes and hit select, the results are displayed, but then checkboxes lose their checked state and that will make users confused what they checked. I am trying to presist the checkboxes state after the page refresh. I am not able to acheive this yet, but I am hopeful its doable. Can someone help me in the right direction?
Emergency Centers<input name="LocType" type="checkbox" value="Emergency"/> 
Out-Patient Centers<input name="LocType" type="checkbox" value="Out-Patient"/> 
Facilities<input name="LocType" type="checkbox" value="Facility"/>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit"><span>Search</span></a></div>
$(document).ready(function() {
var url = "http://mysite/sites/dev/contact-us/Pages/LocationSearchTestPage.aspx?s=bcs_locations";
$('a.searchButton').click(function(){
var checkboxValues = $("input[name=LocType]:checked").map(function() {
return "\"" + $(this).val() + "\"";}).get().join(" OR ");
//Now use url variable which has all the checked LocType checkboxes values and jump to url
window.location = url+'&k='+checkboxValues;
});
//Keep the selected checked on page redirect
var value = window.location.href.match(/[?&]k=([^&#]+)/) || [];
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
}
});
not sure if you're still interested in this, but I had the same problem a little while ago, and found this generic piece of JS that persist checkbox states:
// This function reads the cookie and checks/unchecks all elements
// that have been stored inside. It will NOT mess with checkboxes
// whose state has not yet been recorded at all.
function restorePersistedCheckBoxes() {
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
var el = document.getElementById(aPair[0]);
if(el) {
el.checked = aPair[1] == '1';
}
}
}
// This function takes as input an input type="checkbox" element and
// stores its check state in the persistence cookie. It is smart
// enough to add or replace the state as appropriate, and not affect
// the stored state of other checkboxes.
function persistCheckBox(el) {
var found = false;
var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
if(aPair[0] == el.id) {
// State for this checkbox was already present; replace it
aStatus[i] = currentStateFragment;
found = true;
break;
}
}
if(!found) {
// State for this checkbox wasn't present; add it
aStatus.push(currentStateFragment);
}
// Now that the array has our info stored, persist it
setPersistedCheckStatus(aStatus);
}
// This function simply returns the checkbox persistence status as
// an array of strings. "Hides" the fact that the data is stored
// in a cookie.
function getPersistedCheckStatus() {
var stored = getPersistenceCookie();
return stored.split(',');
}
// This function stores an array of strings that represents the
// checkbox persistence status. "Hides" the fact that the data is stored
// in a cookie.
function setPersistedCheckStatus(aStatus) {
setPersistenceCookie(aStatus.join(','));
}
// Retrieve the value of the persistence cookie.
function getPersistenceCookie()
{
// cookies are separated by semicolons
var aCookie = document.cookie.split('; ');
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split('=');
if ('JS_PERSISTENCE_COOKIE' == aCrumb[0])
return unescape(aCrumb[1]);
}
return ''; // cookie does not exist
}
// Sets the value of the persistence cookie.
// Does not affect other cookies that may be present.
function setPersistenceCookie(sValue) {
document.cookie = 'JS_PERSISTENCE_COOKIE=' + escape(sValue);
}
// Removes the persistence cookie.
function clearPersistenceCookie() {
document.cookie = 'JS_PERSISTENCE_COOKIE=' +
';expires=Fri, 31 Dec 1999 23:59:59 GMT;';
}
Just make sure your checkboxes have an onChange= persistCheckBox(this); attached to them
eg.
<label for= "LocType">User Preference</label>
<input name= "LocType" type= "checkbox" onChange= persistCheckBox(this);"/>
And also an onLoad in your opening body tag:
<body onload="restorePersistedCheckBoxes();">
I would be more inclined to go with HTML5 web storage (faster and more secure) but cookies would also do the job. Here is a link to some samples using HTML5 http://www.w3schools.com/html5/html5_webstorage.asp

Categories

Resources