Auto Update Amount (USD) using onchange with javascript - javascript

I need help with this code. I have looked at tons of related questions but none has helped so far. Please help. These are exactly what I need:
To auto-update "Amount(USD)" once the value of "Amount(NGN)" is changed. Preferably with Vanilla Js.
I would also like to pick the final value of "Amount(USD)" and store in a PHP session to use in other pages.
See my code below:
<?php $grandTotal=10; ?>
<script type="text/javascript">
function calculateTotal() {
var nairaRate = document.pricecalculator.nairaRateToday.value; //get NGN rate today from admin and assign to nairaRate
dollarValue = eval(document.pricecalculator.nairaInput.value * nairaRate); //multiply nairaInput by nairaRate to get dollarValue
document.getElementById('dollar').innerHTML = dollarValue; //pass dollarValue to dollar to show auto-calculation onscreen
}
</script>
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" name="nairaInput" onchange="calculateTotal()" value="1" /> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>

I was able to solve the problem like this:
<?php $grandTotal=10; ?> // set PHP variable
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" id="naira-input" name="naira-input" onchange="calculateTotl()" value="1"/> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
</form>
<script type="text/javascript">
function calculateTotl() {
var nairaRate = document.getElementById("naira-input").value;
// Select your current input
let phpval = "<?= $grandTotal ?>"; // grab php value
var dollarResult = document.querySelector('#dollar');
var total = Number(nairaRate) * Number(phpval); evaluate current input * php value
return dollarResult.innerHTML = total; // write result to #dollar
}
</script>

Try this (worked for me):
var ngn = document.getElementById('ngn');
var dollar = document.getElementById('dollar');
ngn.onchange = ()=>{dollar.innerText=ngn.value*0.0026}

Check the following code. I have used a hardcoded value, that is 7 as nairaRate
let nairaInput = document.querySelector("input[name='NairaValue']")
nairaInput.addEventListener('change', (e) => calculateTotal(e.target.value, 7))
function calculateTotal(input, nairaRate) {
var resultInDollar = document.querySelector('#dollar');
var total = Number(input) / Number(nairaRate);
return resultInDollar.innerHTML = total
}
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC) Naira At 7</legend>
<label>Amount (NGN)</label><input type="number" name="NairaValue" onchange="calculateTotal()" value="0" /> <br />
<label>Amount (USD):</label><span id="dollar">0</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
Good Luck!

Related

Does not change value when I change a date

This system calculates the days between two dates. That number of days is multiplied by a value. But when the client wants to change the departure date, the total value does not change.
<?php
date_default_timezone_set('America/Argentina/Buenos_Aires');
$tarjeta = 200;
$efectivo = $tarjeta*0.5;
?>
<script>
function data(valor) {
let ingreso = document.getElementById("ingreso").value;
let retiro = document.getElementById("retiro").value;
let fechaInicio = new Date(ingreso).getTime();
let fechaFin = new Date(retiro).getTime();
let diff = fechaFin - fechaInicio; //Diferencia en milisegundos
let dias = diff/(1000*60*60*24); //Diferencia en dias
document.getElementById("totaldias").value = dias;
document.getElementById("valor").value = dias*valor;
document.getElementById("dolares").value = valor*tasa_cambio;
}
Form
<h2>Sistema</h2>
<form action="" method="post">
<input type="date" name="ingreso" id="ingreso" autocomplete="off"><br>
<input type="date" name="salida" id="retiro" autocomplete="off"><br>
<input type="radio" id="efectivo" name="pago" value="efectivo" onChange="data(<?php echo $tarjeta;?>)">
<label for="efectivo">Tarjeta 100%</label><br>
<input type="radio" id="tarjeta" name="pago" value="tarjeta" onChange="data(<?php echo $efectivo;?>)">
<label for="tarjeta">Tarjeta 50%</label><br>
<label for="totaldias">Total dias</label>
<input type="text" name="dias" id="totaldias" readonly="readonly"><br>
<label for="valor">A pagar</label>
<input type="text" name="valor" id="valor" readonly="readonly">
</form>
Make sure you perform the recalculation when any input changes, not only the radio buttons. A good way to do this: in the JavaScript code, listen to all "change" events that happen in the HTML document. If you do it like that, you should remove the onChange attributes that are currently in the HTML.
The data function has a parameter with the price per day, but it would be better if the function would not have that parameter, but would itself look at the radio button that is selected, and conclude from that selection which price to use.
Some other issues to fix:
The HTML part is missing a (read-only) input element for "dolares" (which you reference in the JS code).
The calculation of the price in dollars would need to also use valor in its formula.
The variable tasa_cambio is not defined.
When some dates are not yet filled in, it should not output something like "NaN", but maybe just leave the result empty.
So here is how the code would look -- check the comments:
<?php
date_default_timezone_set('America/Argentina/Buenos_Aires');
$tarjeta = 200;
$efectivo = $tarjeta*0.5;
$tasa_cambio = 1.13; // Need to define this variable
?>
<script>
const tasa_cambio = <?=$tasa_cambio?>; // Need to define this variable
function data(valor) {
let ingreso = document.getElementById("ingreso").value;
let retiro = document.getElementById("retiro").value;
let fechaInicio = new Date(ingreso).getTime();
let fechaFin = new Date(retiro).getTime();
let diff = fechaFin - fechaInicio;
let dias = diff/(1000*60*60*24);
// Clear the output when not all values available, so add: || ""
document.getElementById("totaldias").value = dias || "";
document.getElementById("valor").value = dias*valor || "";
// Must multiply with number of days also:
document.getElementById("dolares").value = valor*dias*tasa_cambio || "";
}
// Use this listener instead of onChange attributes.
document.addEventListener("change", function () {
// Inject the two PHP values in this expression:
data(document.getElementById("tarjeta").checked ? <?=$tarjeta?> : <?= $efectivo?>);
});
Form:
<h2>Sistema</h2>
<form action="" method="post">
<input type="date" name="ingreso" id="ingreso" autocomplete="off"><br>
<input type="date" name="salida" id="retiro" autocomplete="off"><br>
<input type="radio" id="efectivo" name="pago" value="efectivo">
<label for="efectivo">Tarjeta 100%</label><br>
<input type="radio" id="tarjeta" name="pago" value="tarjeta">
<label for="tarjeta">Tarjeta 50%</label><br>
<label for="totaldias">Total dias</label>
<input type="text" name="dias" id="totaldias" readonly="readonly"><br>
<label for="valor">A pagar</label>
<input type="text" name="valor" id="valor" readonly="readonly"><br>
<!-- Add the follow element -->
<label for="dolares">Dolares</label>
<input type="text" id="dolares" readonly="readonly"><br>
</form>

I am having trouble with HTML Javascript inclusion

I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you

Send a Javascript array in a mail

I have an HTML form to retrieve some options from checkboxes:
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select a Menu</legend>
<label>
<input type="radio" name="selectedmenu" checked value="menu01" ape-qty='8' ent-qty='1' pes-qty='1' sor-qty='1' car-qty='1' pos-qty='1' data-price='95' />
<span>First Item</span>
</label>
...(more)...
</fieldset>
<fieldset>
<legend id='aperitivosPrompt'>Elegir Aperitivos</legend>
<label>
<input type='checkbox' name='aperitivos' value="1" />
<span>Item 1</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="2" />
<span>Item 2</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="3" />
<span>Item 3</span>
</label>
...(more)...
</fieldset>
<fieldset>
<input type="submit" value="Enviar" />
</fieldset>
</form>
Then I send this variables to a JavaScript file and I save all checkboxes options in multiple arrays
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
aperitivos = document.getElementsByName('aperitivos'),
aperitivosPrompt = document.getElementById('aperitivosPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
aperitivosAllowed = 0,
currentSelectionAperitivos = [],
currency = '€';
function handleAperitivos(e) {
var count = getSelectedCountApe();
if (count > aperitivosAllowed) {
resetSelectApe();
} else {
currentSelectionAperitivos = getSelectedValuesApe();
}
}
...(more)...
function getSelectedCountApe() {
var count = 0;
for (var i = 0; i < aperitivos.length; i++) {
if (aperitivos[i].checked) count++;
}
return count;
}
...(more)...
So, how can I send these arrays named currentSelectionAperitivos = [] in an email? I want that after user selects all his options, I receive an email in my inbox with his selected options.
I think that I must connect this form and JS file with a PHP function and send emails from there. Anyway, how can I do this?
-EDITED-
I tried a solution with JSON:
for (var i = 0; i < aperitivos.length; i++) {
var item = {
"valor": i,
"etiqueta": aperitivos[i].value
};
currentSelectionAperitivos.push(item);
}
currentJSON = JSON.stringify({currentSelectionAperitivos:currentSelectionAperitivos});
console.log(currentJSON);
So now I get in browser console all "values" from fields <input> of the HTML form. But not only CHECKED values and anyway, what I need now is to get this JSON.stringify and send it by mail with PHP.
Write a PHP script to send the email, change the form action to post on this script.
Attention: this is untested.
Change your form to:
<form action="mail.php"...>
</form>
Create mail.php like
<?php
ob_start();
var_dump($_POST);
$result = ob_get_clean();
mail ( 'your#email.com' , 'subject' , $result);
?>
Otherwise you could use JSON.stringify and an API to send the E-Mail with JS.
I found a good solution for my needs. I get all 'checked' values and I create an email with theme.
So, HTML form:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript' src='http://sisyphus-js.herokuapp.com/assets/application-09059f9f54cc3c3bff98487cf866644b.js'></script>
</head>
<body>
<form action="configurador.php" method="post" id="menuform" name="menuform">
<fieldset>
<legend id='itemPrompt'>Choose Item</legend>
<label>
<input type='checkbox' name='item' value="Value#01" />
<span>Value#01</span>
</label>
(...more...)
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
</body>
So there I have all my 'checkboxes' with values and names. I made some JavaScript functions but most important one is this one where I retrieve all values and send theme in an email:
function sendMail() {
var mailbody = "My Configurator: \n\n"
+ $('input[name="item"]')
.map(function(id, box){ return (box.checked ? "[x]" : "[_]") + " " + box.value;})
.get()
.join("\n");
var link = "mailto:mail#mail.com"
+ "?cc="
+ "&subject=" + escape("Configurator - Subject")
+ "&body=" + escape(mailbody);
window.location.href = link;
}
$(function(){
$( "#menuform" ).sisyphus();
});
And it's OK with just this. But I'm getting all checkboxes, even not checked ones, in that email. And could be perfect if I don't have to open a client mail, just send that mail from my server automatically.
Any solution for this variation?

Update an input field when another input field is updated

I can't get this to work.
I got two forms, "mult" and "mult2" with a script making some simple calculations running through both. Both fields are dependent on data in another form called "recipe".
The thing is, i can actually get one of the forms to work doing it like i have done (see all my code under here) - the weird thing is that it's only mult2 that works and does all the calculations. Mult1 is not doing anything. The fields that needs to be updated in the end is "gravity" and "gravity2" - and only "gravity2" gets updated with the result of the calculation.
I know it's some long code bits here, but hope you can help me..
Here is the "recipe" form:
<form name="recipe">
<input type="text" size="1" maxlength="3" name="batchVal" value="30" onChange="calculate(malt1); calculate(malt2)"></td>
<input type="text" size="1" maxlength="3" name="efficiencyVal" value="75" onChange="calculate(malt1); calculate(malt2)"></td>
</form>
Here is the two forms, "mult" and "mult2" that both need the same datainputs from "recipe" form:
<form name="mult">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal" size="1" maxlength="5" value="0" onChange="calculate(malt1)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal" id="ppg" onMouseMove="calculate(malt1)">
</form>
<form name="mult2">
<select id="malt" name="malt" onChange="UpdateNextField(this,'ppg2')">
<option>Choose fermentable..</option>
<?php
$query = $mysqli->prepare("SELECT id,maltname,maltebc,maltppg FROM malt WHERE mainid = ?");
$mainidcolumn = "1";
/* bind parameters */
$query->bind_param("i", $mainidcolumn);
$query->execute();
$menu_result = $query->get_result();
/* now you can fetch the results into an array */
while ($menu = $menu_result->fetch_assoc()) {
echo '<option value="'.$menu['maltppg'].'">' . $menu['maltname'] . ' ' . $menu['maltebc'] . ' EBC</option>';
}
echo '</select>';
?>
<input type="text" id="ebcfield" size="1" maxlength="3">
<input type="text" name="weightVal2" size="1" maxlength="5" value="0" onChange="calculate(malt2)">
<input name="grainpercent" type="text" id="grainpercent" size="1" maxlength="2">
<input type="text" id="gravity2" size="1" value="0" maxlength="4">
<input name="graincolor" type="text" id="graincolor" size="1" maxlength="3">
<input type="text" name="ppgVal2" id="ppg2" onMouseMove="calculate(malt2)">
</form>
And finally the javascript that does the calculations based on data in the input fields. Calculate(malt1) and Calculate(malt2) does the same thing, it's just two instances of the same calculation.
<script type = "text/javascript">
function UpdateNextField(which,ppg) {
document.getElementById(ppg).value = which.value;
}
function UpdateNextField(which,ppg2) {
document.getElementById(ppg2).value = which.value;
}
</script>
<!-- calculations for malt 1-5 -->
<!-- form 1 - fermentable 1 -->
<script type="text/javascript">
function calculate(malt1){
var weightVal = document.mult.weightVal.value;
var ppgVal = document.mult.ppgVal.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue = 0;
var showValue = ((weightVal * ppgVal * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue = Math.round(showValue * 1) / 1;
if (!isNaN(showValue)) {
document.getElementById('gravity').value = showValue;
}
}
function calculate(malt2){
var weightVal2 = document.mult2.weightVal2.value;
var ppgVal2 = document.mult2.ppgVal2.value;
var batchVal = document.recipe.batchVal.value;
var efficiencyVal = document.recipe.efficiencyVal.value;
var showValue2 = 0;
var showValue2 = ((weightVal2 * ppgVal2 * 0.000008345) * (efficiencyVal) * 10) / batchVal + (1000);
showValue2 = Math.round(showValue2 * 1) / 1;
if (!isNaN(showValue2)) {
document.getElementById('gravity2').value = showValue2;
}
}
</script>
You have a few problems with your function names and duplicate IDs, as noted by Jay and LcLk. But, assuming you fix these, you can save a lot of time and grief by using jQuery. For example:
HTML
<input type="text" id="first" />
<input type="text" id="second" />
Javascript
$("#first").keypress(function(){
/* your custom code goes here */
console.log("A key was pressed.");
});
What this says is that anytime a key is pressed while the first input is selected, it will print out A key was pressed in the console. You can then either directly call your calculation functions from within that anonymous inner function, or pass them directly into keypress();.

How to add/subtract from a number that comes from a php variable

What I am trying to do is update a Total Price based on select options. The initial price amount comes from a session variable. I have gotten the variable to pass into Javascript, but i can not seem to add/subtract from that number when using the form.
What am I missing?
thanks for the help.
<script>
$(document).ready(function()
{
var phonePrice = "<?php echo $q2; ?>";
var total = phonePrice;
function calcTotal()
{
$("input:checked").each(function()
{
//This happens for each checked input field
var value = $(this).attr("value");
total += parseInt(value);
});
}
//This happens when the page loads
calcTotal();
$("form").before('<p class="total">Total: <strong>' + total + '</strong></p>');
$(":submit").before('<p class="total">Total: <strong>' + total + '</strong></p>');
$("input:checkbox, input:radio").click(function()
{
total = phonePrice;
calcTotal();
$("p.total").html("Total: <strong>" + total + "</strong>");
});
});
</script>
The Form looks like this
<form action="" method="post">
<fieldset id="delivery_speed">
<legend>Options
</legend><ol>
<li>
<input type="radio" name="speed" id="speed_1day" value="49" />
<label for="speed_1day">Option 1 ($49)</label>
</li>
<li>
<input type="radio" name="speed" id="speed_3days" value="0" checked />
<label for="speed_3days">Option 2 (no charge)</label>
</li>
<li>
<input type="radio" name="speed" id="speed_5days" value="-39" />
<label for="speed_5days">Option 3 (-$39)</label>
</li>
</ol>
</fieldset>
<fieldset id="browser_support">
<legend>Additional Choices</legend>
<p>
<input type="checkbox" name="browser" id="browser" value="100" />
<label for="browser">Checkbox 1 ($100)</label>
</p>
</fieldset>
<p><input id="submit" type="submit" value="Continue to Checkout >>"></p>
</form>
var phonePrice = "<?php echo $q2; ?>";
assuming that the php code spits out something like this when rendered:
var phonePrice = "99.99";
The quotes make it a string and not a number. Remove the quotes and you will have a number that will add correctly.
var phonePrice = <?php echo $q2; ?>;
Remove the quotes from phonePrice:
var phonePrice = <?php echo $q2; ?>;
The problem comes when you do total += parseInt(value). Since you define phonePrice as
var phonePrice = "<?php echo $q2; ?>";
it does string concatenation but not sum.
You should either unquote the value
var phonePrice = <?php echo $q2; ?>;
or add another type conversion:
var phonePrice = parseInt("<?php echo $q2; ?>", 10);

Categories

Resources