Does not change value when I change a date - javascript

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>

Related

how can we display html form values as many times as the user insert them by pressing submit button each time?

<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id ="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id ="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id ="submit" ><br>
</form>
<p id="sum"></p>
<div id="sumoftotal"></div>
<body>
<script language="JavaScript">
document.getElementById("submit").onclick=function (){
let firstName = document.getElementById("First-name").value;
let lastName= document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total =parseInt(num1) + parseInt(num2);
document.getElementById("sum").innerHTML=(`${firstName} ${lastName} ${total }`)
}
</script>
</body>
my problem can be numbered:
number 1: when I press the submit button, input values show up, BUT when I want to insert a different data, the previous one disappear. I studied about it, because whatever comes in the function scope become local we cannot apply it outside, BUT I don't know how to change it.
number 2: I want to have the sum of total weights I insert at the end of my list, I know we can do this by loop, BUT I need something simpler and more preliminary because I am a novice and it would be a big jump for the time being.
all in all, I would be happy if anyone could help me.
Here is the primary and most basic approach.
var data = document.getElementById('data');
var weightElement = document.getElementById('total-weight');
document.getElementById("submit").onclick = function() {
/* Getting data */
let firstName = document.getElementById("First-name").value;
let lastName = document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total = parseInt(num1) + parseInt(num2);
/* Appending element */
data.innerHTML = data.innerHTML + `First Name - ${firstName}, Last Name - ${lastName}, Weight - ${total} <br/>`;
weightElement.innerHTML = parseInt(weightElement.innerHTML) + total;
}
<body>
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id="submit"><br>
</form>
<div id="data"></div>
<div>Total weight = <span id="total-weight">0</span></div>
</body>

Auto Update Amount (USD) using onchange with 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!

Collect all value from input html form to object of javascript

Normally if I add a new input tag I also have to add in Javascript.
I try to collect all value from input tag,
So how to pass value into an object by loop
use tag input name to be object key name also.
Try to use for count
document.getElementById("form1").elements.length
seem it collected the button tag also, how to void it
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" onClick="fc1()" value="Save">
</form>
for(i=0;......)
{
obj.value+'i' = document.forms["form1"]["value"+ (i+1)].value;
}
Same result as this.
function fc1(){
this.value1 = document.forms["form1"]["value1"].value;
this.value2 = document.forms["form1"]["value2"].value;
this.value3 = document.forms["form1"]["value3"].value;
this.value4 = document.forms["form1"]["value4"].value;
const obj = {
"value1": this.value1,
"value2": this.value2,
"value3": this.value3,
"value4": this.value4
};
}
I usually grab inputs by their ID or class:
<input type="text" id="value1">
then grab the value:
const value1 = document.getElementById('value1').value
to cut down on code, maybe throw it in an array:
const valueArray = [value1, value2, value3]
then you can do something like this:
const allValues = {}
valueArray.forEach((value, index) => {
allValues[`value${index + 1}`] = value
})
now when you log allValues you should have what you want. Note, I am using some es6.
What about this ?
var obj = {};
var form = document.getElementById("form1");
form.children.forEach(function(elm){
if(elm.type === 'text'){
obj[elm.name] = elm.value;
}
});
console.log(obj);
try giving same 'class' or 'name' attribute to the text fields.
try var x = document.getElementsByClassName("example");
which gives you the list of all elements with the class name as "example'. Then you can loop around based on the length of x.
References:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try this:
var input = document.forms[0].querySelectorAll('input[type=text]');
var result = Array.from(input).reduce((r, ele) => {
r[ele.name] = ele.value;
return r;
}, {});
console.log(result);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
If you used something like .. I think it will work. :)
var myObj = {};
var elems = document.getElementsByTagName('input'), i;
for (i in elems) {
myObj[value + i] = myObj[i].value;
}
return from getElementsByTagName is an array of all matching tags. there are some wizard answers in here ha. :)
document.querySelectorAll is made for this.
document.querySelectorAll("form[name='form1'] input[type='text']")
will return all input fields of type text in form1 as HTML nodes.
let elements = document.querySelectorAll("form[name='form1'] input[type='text']");
elements.forEach(e => console.log(e.value));
...logs the values of the input fields. Don't make things harder on yourself by hard coding classes or ID's, and this will allow you to target the input elements you need without additional checks or without fetching every input on the page.
Example:
const values = {};
document.querySelectorAll("form[name='form1'] input[type='text']").forEach(element => values[element.name] = element.value);
console.log(values);
<form name="form1">
<input type="text" name="value1" value=1>
<input type="text" name="value2" value=2>
<input type="text" name="value3" value=3>
<input type="text" name="value4" value=4>
<input type="button" id="save" onclick="fc1()" value="Save">
</form>
This is an alternative solution done with jQuery.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
//jQuery solution
const obj = {}
$('#save').click(function(e){
var form = $(this).parent();
var inputs = form.children().not(':input[type=button]');
$.each( inputs, function(){
obj[$(this).attr('name')] = $(this).val();
});
console.log(obj);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>jQuery solution</h2>
<form name="form1">
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="save" value="Save">
</form>
JS Solution
//JS Solution
const objs = {}
var button = document.getElementById('savejs');
var form = document.getElementById('formjs');
var element = {};
button.addEventListener('click', function(){
inputs = form.children;
for(i=0; i < inputs.length; i++){
if(inputs[i].name != ""){
objs[inputs[i].name] = inputs[i].value;
}
}
console.log(objs);
})
<h2>JS solution</h2>
<form name="form1" id='formjs'>
<input type="text" name="value1">
<input type="text" name="value2">
<input type="text" name="value3">
<input type="text" name="value4">
<input type="button" id="savejs" value="Save">
</form>

diffrence of two input fileds returned in another input

I would like to calculate in the simplest way difference of two inputs and return it in the third one.
id="incomeSharedSum" - id="expendituresSharedSum" = id="disposalIncome"
Here is my form:
<label for="%nameRoot%[income]">Total Income:€</label>
<input type="text" data-sumSource=".incomePart<?php echo $personOrder; ?>" name="%nameRoot%[income]" id="incomeSharedSum"/>
<label for="%nameRoot%[expenditures]">Total Expenditures: €</label>
<input type="text" data-sumSource=".expendituresPart<?php echo $personOrder; ?>" name="%nameRoot%[expenditures]" id="expendituresSharedSum"/>
<label for="%nameRoot%[disposalincome]">Monthly Disposal Income: €</label>
<input type="text" name="%nameRoot%[disposalincome]" id="disposalIncome"/>
Appreciate your help on this very basic question. Thank you.
==========EDIT==========21/01/2016
I have some progress but dont know now how to modyfi js to calculate difference rather than sum:
<label for="%nameRoot%[income]">Total Income: €</label>
<input onblur="updateDiff('#disposalIncome');" type="text" data-sumSource=".incomePart<?php echo $personOrder; ?>" name="%nameRoot%[income]" class="form-control disposalIncome" id="incomeSharedSum"/>
<label for="%nameRoot%[expenditures]">Total Expenditures: €</label>
<input onblur="updateDiff('#disposalIncome');" type="text" data-sumSource=".expendituresPart<?php echo $personOrder; ?>" name="%nameRoot%[expenditures]" class="form-control calc disposalIncome" id="expendituresSharedSum"/>
<label for="%nameRoot%[disposalincome]" class="col-sm-4 field-label">Monthly Disposal Income: €</label>
<input type="text" data-sumSource=".disposalIncome<?php echo $personOrder; ?>" name="%nameRoot%[disposalIncome]" class="form-control" id="disposalIncome"/>
and using this piece of js code:
function updateDiff(outputFieldSelector){
var outputField = $(outputFieldSelector);
var sum=0;
$(outputField.attr('data-sumSource')).each(function(){
sum+=Number($(this).val());
});
outputField.val(sum);
How to modyfi this line:
sum+=Number($(this).val());
To get difference (in my case two fields) : Total Income - Total Expenditures = Disposal Income.
this function will do the sum and put the value in third textbox
function calculateSum()
{
var incomeSharedSum= parseInt( document.getElementById( "incomeSharedSum" ).value );
incomeSharedSum = isNaN( incomeSharedSum ) ? 0 : incomeSharedSum;
var expendituresSharedSum = parseInt( document.getElementById( "expendituresSharedSum" ).value );
expendituresSharedSum = isNaN( expendituresSharedSum ) ? 0 : expendituresSharedSum ;
document.getElementById( "disposalIncome" ).value = incomeSharedSum + expendituresSharedSum;
}
you can invoke this method on which event (like a button click or blur event of one of the first two boxes)
Basically using .value for each of the two input fields, do the subtraction and set the value to the .value of the third input field. check this JS Fiddle - updated 2
var inputs = document.getElementsByClassName('calc'),
income = document.getElementById('incomeSharedSum'),
expenditures = document.getElementById('expendituresSharedSum'),
gTotal = document.getElementById('gTotal');
for (var i in inputs) {
this.addEventListener('change', function() {
gTotal.value = +income.value - +expenditures.value;
});
}
<label for="incomeSharedSum">Total Income:€</label>
<input type="text" id="incomeSharedSum" class="calc" />
<br>
<label for="xpendituresSharedSum" class="col-sm-4 field-label">Total Expenditures: €</label>
<input type="text" id="expendituresSharedSum" class="calc" />
<hr>
<label for="gTotal" class="col-sm-4 field-label">final: €</label>
<input type="text" id="gTotal" />
if you want to add fractions, change the it into this:
gTotal.value = (+income.value - +expenditures.value).toFixed(2);
where 2 is how many digits after the period, if 0 it will output integer.
JS Fiddle 2

2 name attributes for a field in a form

I have a script that calculates the values in each and shows the calulated values. At the end it also calculates the already calculated values from all div's
Here is the html code:
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
The problem is that I want to put all fields in a form and then submit them to a database.
However, all divs contain two input fields with name "r" and "p".
So, I am kind of stuck here because I cannot figure out how to make the names unique or how to have them passed to the DB using POST.
This is what the calculating script looks like:
<script type="text/javascript">//<![CDATA[
//any time the amount changes
$(document).ready(function() {
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
//]]>
</script>
HTML:
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
PHP:
for ($i = 0; $i < count($_POST['p']); $i++) {
$rate = $_POST['r'][$i];
$pack = $_POST['p'][$i];
// do something with $rate and $pack
}
Since the browser submits all inputs (even if no value has been entered) and by specification it submits them in the order they are defined in the HTML code, you can rely that the elements in the two $_POST arrays will line up and the corresponding rate and pack will be received at the same index in the respective array.

Categories

Resources