Repeat / Update Hidden variable - javascript

I'm updating the amount of a PayPal button with a variable amount. I'm getting the amount like this:
<input type="hidden" name="amount" value="" />
var amount = document.querySelector('.total-box > span').innerText;
var hidden = document.querySelector("input[name='amount']");
hidden.value = amount;
console.log(hidden.value);
That amount updates .total-box > span when paypal fees are added to the total.
Therfore I need the console log(hidden.value) to update as well so it updates the PayPal amount field. Currently console log(hidden.value) is only running one time on page load, and doesn't update or get passed to PayPal.
Here is a JSFiddle to better explain what is going on.
Any help would be appreciated.

Related

Calculations based on radio button choices

I am using a MEAN stack for my web project. The front end is a simple registration form that asks for several user inputs. For example, it says "how many products are you buying?" The next question is a radio button. It says is this product large or small? My question is the following: the calculation to get the cost of the order is #products*42+(12 if large is selected) or #products*42+(0 if small is selected). How do I code this in javascript(I am using node in my backend). In other words, how do I tell my calculation code that when user selects a radio button you need to add a following number and how do I pass on the number of products typed to my formulas? I have started by assigning value=1 for small and value=2 for large radio button option. Just a general example would be helpful as I can code the details and update the formulas once I get around this problem. Thank you
If you want to do the calculation on the client side and the elements are in an HTML form like:
<h1>Radio Buttons</h1>
<form name="catch-radio" method="post">
<div class="input">
<span class="label">How many products are you buying?</span>
<input id="product-count" type="text" name="product_count" value="0"/>
<br/>
<span class="label">Is this product large or small?</span>
<br/>
<span class="label">Large</span>
<input type="radio" name="product-size" value="12" checked="checked"/>
<br/>
<span class="label">Small</span>
<input type="radio" name="product-size" value="0"/>
</div>
</form>
<div>
<h2>Cost of order:</h2>
<p id="calculation"></p>
</div>
with an input for the number of products (with an id of 'product-count') and radio buttons corresponding to the product size (named 'product-size'), you can calculate the cost and output it to an element on the page (with an id of 'calculation') by adding event handlers to the form fields to register a change in the form, and then from those handlers calling a function to perform the calculation and update the page accordingly like so:
// Cost is the count of products purchased multipled by 42 then added
// to 12 in the case that the product is large, and zero in the case
// that the product is small
function calculate_cost() {
let count = parseInt(document.getElementById('product-count').value);
if (count > 0) {
let size = 0;
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
if (document.getElementsByName('product-size')[i].checked) {
size = parseInt( document.getElementsByName('product-size')[i].value);
break;
}
}
let cost = count * 42 + size
document.getElementById('calculation').innerHTML = cost;
}
}
// handlers for form input change
// call calculate_cost() on change
// note that the text input is an on-change event but for radio buttons
// an onclick handler is needed for each button
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
document.getElementsByName('product-size')[i].onclick = function() {
calculate_cost();
}
}
document.getElementById('product-count').onchange = function() {
calculate_cost();
}
I put up a quick demo of this on CodePen here: http://codepen.io/P1xt/pen/yOKqXP/
The particularly interesting bit is that for the radio buttons, you need to add a click handler for each button separately (and it must be a click not a change handler, and to figure out which radio is currently selected, you need to explicitly check each one to see if it's 'checked'.
Note: If you're looking to do your calculations on the server-side, you'd need to submit the form, then collect the product-count and product-size from the submitted form elements in order to perform the calculation.
Why not use 0 and 12 as the values for the radio buttons, then the backend can just add the selected value?

Count clicked checkboxes, even after refresh

I am trying to keep count of how many times the check boxes have been clicked on my site, the check boxes are used for filters (for men, women, age, etc).
At the moment I have this code
jQuery('[id^="checkbox"] input').each(
function (index, element) {
jQuery(this).click(
function () {
console.debug("Hello");
}
);
}
);
Which will count (in console) how many times a check box has been click (with an id starting with checkbox), but because the page refreshes the information (and url) with each click, it will only count the first click, and the rest will not be counted.
Is there anyway to carry on counting after the page has been refreshed?
Thanks
To have a persistent count of all checkboxes being checked across all users, you need to have a central total which all counts update. This will be quite tricky for even large sites like YouTube still struggle with this (although to a lesser extent).
I am unaware that this can be accomplished purely in JS (if anyone knows, please edit this answer) and you will likely need some sort of back-end code.
One approach you could take would be:
update a local total of checked checkboxes on click
set a timer of 1/2 seconds on click
once the timer ends, send an ajax request to a back-end page
back-end page receives the update, update the central total
There are many other approaches you could take. You're likely to run into issues like, the central total might not be very accurate (if ajax requests are interrupted) and your bandwidth usage increasing due to the ajax requests.
Gennady Dogaev shared some really good code which posts the id of the checkbox and it's value to another page. This page would likely have the logic to update a database or something similar to track which checkboxes are being used.
<body>
<input type="checkbox" id="check_1" /> 1
<input type="checkbox" id="check_2" /> 2
<input type="checkbox" id="check_3" /> 3
</body>
$(function(){
$("input[type=checkbox]").click(function(){
var box = $(this);
var data = {
id: box.prop('id'),
checked: box.is(':checked')
};
$.get('https://stackoverflow.com/', data).always(function(response){
console.log('server responded', response);
/*Click registered, do what you want here*/
});
});
});
https://jsfiddle.net/nrLpxLuf/
The below answer was to help count all checked checkboxes on the page and update the total locally. I've left it here for reference.
You don't need to loop over all elements to attach a single click event to all of them.
Instead attach a click event to a collection of checkboxes and then update a total variable from within the click function.
var $inputs = $('[id^="checkbox"] input');
var total = $inputs.filter(':checked').length; //this will be 0 if none are found
$inputs.on('click', function(event) {
if($(this).is(':checked')) {
total++;
} else {
total--;
}
console.log(total);
});
If you only want to see if it has been clicked, just add to the total.
You need to set value on load if you want to count the checked after refresh.
var total = 0;
$(document).ready(function (event) {
//onload count for the checked checkboxes and set total value
total = $('[id^="checkbox"] input:checked').length;
$('[id^="checkbox"] input').on('click', function (event) {
$(this).prop('checked') ? total++ :total--;
});
});

Form Code with Javascript Real Time Calculation

I have been looking for awhile but can not figure how to code the below example:
Enter in Weight of Cans:
(ADD BUTTON) - Purpose to add another input field to enter in additional weight field
Input Field = Weight 1 = 5
Input Field = Weight 2 = 5
Input Field = Weight 3 = 10
Input Field = Weight i = ? (after clicking on ADD)
Then I want in real time for the Total Weight to be calculated so in this case it would be 20 and finaly an estimate of Total Cans with this formula (Total Weight * 150) so in the example Total Cans would be 3000.
I want to use HTML Form and Javascript but I do not know how to handle the Add Button feature so the Total Weight and Total Cans can be calcualted in real time. I am thinking of an array but can not figure the syntax.
Any advice or assistance would be greatly appreicated.
I'm normally against this, but it seems as though you genuinely need help, so here it is. Keep in mind, this is very basic and there are better ways to do this, but I wanted to keep it very simple for you since you're just starting out. First - you really don't need a button. If you want a button, you can assign the function to a button action, but this code automatically calculates the total for you. Also, you'll want to add in some validation, this quick example assumes that everyone always just enters a number like they're supposed to... which never happens, so you'll want to look into some validation as well.
Here is a working example: http://jsfiddle.net/813dL6d3/1/
And the code:
HTML:
<input type="text" id="weight1" onblur="calculateForm();" /><br />
<input type="text" id="weight2" onblur="calculateForm();" /><br />
<input type="text" id="weight3" onblur="calculateForm();" /><br />
<input type="text" id="weightTotal" />
Javascript:
var calculateForm = function () {
document.getElementById("weightTotal").value =
(
Number(document.getElementById("weight1").value) +
Number(document.getElementById("weight2").value) +
Number(document.getElementById("weight3").value)
) * 150;
};

Can I change dyanmic javascript variable depending on user form input?

My question here is if there is a way to change the dynamic price calculation depending on the name a user enters in the input field.
I have code that works very well for calculating a dynamic price in an html form. Here is the code:
Using this input:
<input class="typeahead" type="text" placeholder="Amount" name="Amount"/>
My Javascript then calculates price:
jQuery("input[name='Amount']").change(function () {
if (isNaN(parseFloat(this.value)) || !isFinite(this.value)) {
jQuery(this).val('');
return false;
}
var calc = parseFloat(this.value) * 0.95;
jQuery(this).parents("form").find("input[name='price']").val(calc);
});
That by itself works fantastic. It calculates the amount by .95 and then assigns that value as price.
If I add this into the form:
<input class="stores typeahead" type="text" placeholder="Stores" name="name"/>
What can I do here to be able to calculate the price at different values depending on the store name. For example, if someone enters McDonalds, I want it to calculate at .90. If someone enters Target, I want it to calculate at .92. The previous javascript cannot accomplish this because it calculates everything at .95 instead of being able to change depending on the store entered.
I would prefer to accomplish this with javascript because I'm not very skilled with php.
You can create a Javascript object for this.
var stores = {
"McDonalds" : .90,
"Target" : .92,
}
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
console.log(stores[storeName]); //Output the store cost to console.
Though I think the jQuery lookup function is questionable. I'm sure there is a better way to select that textbox. But that's the general concept you're looking for.

jQuery prepopulate form fields from select box and calculate results

I am building a calculator form to allow people to calculate the cost of running electrical appliances. They can select an appliance, as an example, from a dropdown list and this should prepopulate the text fields with the figures necessary for the calculation. Here is the form:
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
<label>Appliance</label>
<select id="list" >
<option value="select">Select</option>
<option value="dishwasher">Dishwasher</option>
<option value="iron">Iron</option>
</select>
<label>Watts</label> <input name="watts" /><br>
<label>Hours</label> <input name="hours" /> <br>
<label>Price</label> <input name="price" /> <br>
<label>Number</label> <input name="number" /> <br>
<label>Total</label> <input name="total" value="" id="total"></input>
</form>
When a user selects an appliance I want the input fields to be filled something like this:
case 'dishwasher':
$('input[name="watts"]').val('1200');
$('input[name="hours"]').val('20');
$('input[name="price"]').val('10');
$('input[name="number"]').val('1');
Then do some calculation on the figures:
kilowatts = watts / 1000;
kwhours = kilowatts * hours;
costpounds = kwhours * price / 100;
total = costpounds * number
and put the total into the total field in the form, the idea is to also allow the user to change the figures, or even just add their own, in the form and the total updates accordingly. I can get all the individual bits to work, but don't know jquery well enough to put it all together. Help would be greatly appreciated. Thanks!
Here is some javascript / jquery to get you started. There are more efficient ways, but those are very confusing for someone just learning.
//when the document is finished being rendered, this fires
$(document).ready(function(){
//if the user changes the value in the select dd, this fires.
$('#list').change(function(e){
changeInputValues(this.val());
});
// standard JS function to set the input values with defaults for a given drop down. your idea ;)
function changeInputValues(ddValue){
//put your Case 'dishwasher' code here, one case for each Drop down value
//$('input[name="watts"]').val('1200');
//$('input[name="hours"]').val('20');
//$('input[name="price"]').val('10');
//$('input[name="number"]').val('1');
//recalculate the figures
recalculate();
};
// when someone changes an input, but not the Drop Down, we have that on already.
$('input').not('select').change(function(e){
recalculate();
});
function recalculate(){
// get the current values, then do your math
//var currentWatts = $('input[name="watts"]').val();
//var currentHours = $('input[name="hours"]').val();
//....
//var total = 0;
// do more math... whatever you want
//set the 'visible' value
$('input[name="total"]').val(total)
};
});
So basic structure is 2 functions.
Called when the "appliance" select is changed. Takes all the values of the item selected by grabbing the id like $(this)find('selected').attr('id')*. Once you have the id of the select appliance you can use it to pull the correct values from your appliance arrays and then it's easy to $(this).find('name_of_filed').text("value from the array") with a little for each loop.
called when any other field is onChanged (or you can make an update button in case it's annoying to have it constantly updating while you are making multiple changes). Also called at the end of function 1. Takes all the values from the fields, does calculation, inserts into "total" field.
you can certainly break this down much further to smaller pieces if you want it to be more easily edited in the future and to reuse any of this code but if it's going to be a one of then I wouldn't bother splitting it much more than this.
I can get a lot more specific if need be but I figure it's better for you to try and figure specifics out to learn as you go and we here at SO can answer specific questions as you go.
*may not be actuall correct code. I'm lazy and you will learn more this way! ;)

Categories

Resources