Populating a calculated value into another form - javascript

I have a small form that calculates a shipping cost, which is all working fine. I want the user to click Book Now and the fields are then populated.
All the fields have been populated correctly, its just the cost calculation doesn't populate on the form.
This is my code for calculting the cost
var values = [
[20,25,35,40],
[36,42,50,56],
[42,56,52,68],
[60,70,68,72],
];
function updateValue() {
var fromCountry = document.querySelector('input[name="from_country"]:checked').value;
var toCountry = document.querySelector('input[name="to_country"]:checked').value;
var totalValues = values[fromCountry-1][toCountry-1];
var quantity = document.querySelector('select[name="number"]');
var x = parseInt(quantity.value, 10);
if(fromCountry && toCountry) {
document.getElementById('cost').value = (totalValues * x);
}
}
This is the html
<input type="text" id="cost" name="cost" value="0" disabled="disabled" />
Then the other form looks like this:
<label for="cost">Estimated cost</label>
<input type="text" id="cost" name="cost" value="<?php echo $_POST['cost'];?>">
All the other fields populate fine but the cost one doesn't for some reason.

I believe if a text input is disabled its contents are not actually POSTed in the submission. Add a hidden input and populate it with the value and it should be sent in the request.
On the other hand, there is no reason why you cannot perform the same calculation on the server side using the values you do have. There is nothing stopping a savvy user from editing the "cost" on your page to give themself a nice discount.

Related

JS - Prevent append to be added multiple times

I have a form that has a mobile field. On submit button I put an event to add a value to the mobile field (it adds the country region code automatically which is a fixed value of "11"), so when the user clicks on Submit, the JS adds the "11" value to the mobile so the this field goes to the data base like this "1155555555" (the user just typed "55555555").
Ok, the problem is that if the user left an empty field (all fields are required), and clicks on Submit, the form won´t be sent but it will add the value "11" to the mobile field no matter what, and when the user fills up the empty field and click on Submit for the second time, it will add AGAIN the value "11", so the mobile goes like "111155555555", and so on and so forth.
Basically, what I need is to prevent this function from happening multiple times. It has to happen only once. How do I achieve this using JS?
HTML:
<input id="mobile" name="MOBILE" type="tel"><input type="number" value="11" id="front" class="hide">
<button type="submit" onclick="append11()">SUBMIT</button>
JS:
function append11(){
var mobilenumber = document.getElementById("mobile");
var front = document.getElementById("front").value;
mobilenumber.value=front+mobilenumber.value;
alert(mobilevalue.value);
}
Why you don't append the 11 in the function?
Like:
function append11(){
var mobilenumber = document.getElementById("mobile");
mobilenumber.value="11"+mobilenumber.value;
alert(mobilevalue.value);
}
I think you should heed the comment responses to your original question. Your approach has some risks.
But I'll assume you're a beginner who's just trying to learn how to do something like what you're asking about, so the javascript below applies a few principles you might consider.
function isNumberValid9(num) {
console.log(num, num.length);
//check string length and pattern
//this could be combined into a single regex, e.g.: mobileValue.match("^[0-9]{9}$")
var isValid9 = num.length === 9 && num.match("^[0-9]+$");
console.log(isValid9); //display the value about to be returned
return isValid9;
}
/* Conditionally prepend "11" */
function maybeAppend11() {
var mobilenumber = document.getElementById("mobile");
var mobileValue = mobilenumber.value;
//only prepend "11" if the number matches your expected pattern and length
if (isNumberValid9(mobileValue)) {
var front = document.getElementById("front").value;
mobilenumber.value = front + mobileValue;
}
alert(mobilenumber.value);
}
<input id="mobile" name="MOBILE" type="tel" value="555555555"><input type="number" value="11" id="front" class="hide">
<button type="submit" onclick="maybeAppend11()">SUBMIT</button>

How to check if a page comes after clicking the back button using jQuery?

I have a form where I am calculating the total amount using jQuery.
The function I created for that is updateTotal();
and the form action is another page and the action page has this button:
<button class="btn btn-success" onclick="history.go(-1);" type="submit" name="edit">EDIT</button>
so when the user clicks on the EDIT button page goes back to the form again (first page) and all the filled up details are there except the repetitve fields created using jQuery.
The sample form is here in js fiddle
I just want to run this function updateTotal(); if the user comes to the form by clicking the EDIT (basically browse go back) button..
Is there any way to do this in jQuery?
UPDATES FOR FUTURE REFERENCE - I SOLVED IT LIKE THIS
html:
<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF reqFamount" data-js-input-type="number" />
and the jQuery :
jQuery(document).ready(function() {
var hiddenTot = jQuery('.reqFamount').val() ;
jQuery(".totalAmount").val(hiddenTot);
});
Define a hidden field to store the computed value.
<input type="hidden" id="hiddenTotal" />
Then store the calculated value to the hidden field with Id 'hiddenTotal'.
function updateTotal() {
var price = 0;
$(".inputChangeVal").each(function() {
var t = parseFloat(jQuery(this).val(), 10);
price = price + t;
});
var total = price.toFixed(2);
$(".totalAmount").val(total);
$("#hiddenTotal").val(total);
}
Then when the browse back is triggered the hiddenfield is automatically filled by the browser.
Next check when the document is ready, read the value of hiddenTotal and write to totalAmount.
$(document).ready(function (){
// read value and set value of totalAmount to hiddentotal;
var hiddenTotal = $("#hiddenTotal").val() || 0; //use the hiddenTotal value or if not present set 0 as the default value
$(".totalAmount").val(hiddentotal)
}
Now totalAmount is restored. This even works when you leave the page and return using your browsers history.

JAVASCRIPT HTML no output [duplicate]

I am trying to continuously add to a js variable every time a user enters a value into a box.
So far if they enter '21' the alert will say 'your balance is £12' but then if I enter '15' I want it to say your balance is '27' but instead it says '15' or rather just the latest amount.
The code below:
<form action="" method="get">
<input type="number" value="" id="amountDropped">
<input type="submit" value="Deposit amount" onclick="depositedFunds()">
</form>
var firstAmount = 0;
function depositedFunds(){
var ad = document.getElementById("amountDropped");
firstAmount = +firstAmount + +ad.value;
alert ("Your balance is £" + firstAmount);
};
thanks
The function which makes the change is attached to a submit button.
When the user clicks the button:
The JS runs
The value is updated
The value is alerted
The form is submitted
A new page loads
The new page has var firstAmount = 0; in it
You should:
Set the default value dynamically with server side code. See Unobtrusive JavaScript and
Prevent the default behaviour of the submit button
Using an onclick attribute, you need to return false from the event handler function:
onclick="depositedFunds(); return false;"
Modern code would separate concerns and not tie things so tightly to a specific means of triggering the form submission.
var firstAmount = 0;
function depositedFunds(e) {
e.preventDefault();
var ad = document.getElementById("amountDropped");
firstAmount = +firstAmount + +ad.value;
alert("Your balance is £" + firstAmount);
};
document.querySelector('form').addEventListener('submit', depositedFunds);
<form method="get">
<input type="number" id="amountDropped">
<input type="submit" value="Deposit amount">
</form>

live calculation go next step then back the number became what i set originally

I have done the code for the live calculation which means when the user entered data for all fields, the result will change accordingly. Then my page has a next button which let the user proceed to next step. If the user went to next page and wanted to go back to edit what he have entered, the result will be $0.00 but not the real result, unless the user reenter a value in an input box. Thus, what i want is just when user go back to the page, the result will remain what was showed.
Thank you for your time.
<!doctype html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('input').keyup(function(){
var $rincome = parseInt($('#textfield1').val());
var $rate = parseInt($('#textfield2').val());
var $age = parseInt($('#textfield3').val());
var $rage = parseInt($('#textfield4').val());
var rmoney = fv($rate/100,$rage - $age ,0,$rincome,0);
$('#rmoney').html(rmoney);
});
});
</script>
<form action="process.php" method="post" autocomplete="on">
<b>Income (SGD):</b>
<input type="number" id="textfield1" value="<?php echo $_POST['rincome'];?>" name="rincome" min = "0" />
</p>
<p>
<b>Interest rate (%):
<input type="number" id="textfield2" value="<?php echo $_POST['rate'];?>" name="rate" min = "0" step = "0.1"/>
</p>
<p>
<b>Age:
<input type="number" id="textfield3" value="<?php echo $_POST['age'];?>" name="age" min = "0" max = "70"/>
</p>
<p>
<b>Life expectancy:
<input type="number" id="textfield4" value="<?php echo $_POST['rage'];?>" name="rage" min = "0"/>
</p>
<p>
<b>The total money you will have:$<span id = "rmoney">0.00</span>
</p>
<script>
function fv(r,n,p,pv)
{
var sum = pv;
for (var i=0;i<n;i++ )
{
sum += sum*r + p;
}
return sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}
</script>
<p style="text-align:center" style="font-size:160%">
<input type="submit" name="submit" Value="Next"/>
<input type="reset" value="Reset" />
</p>
</form>
<?php
session_start();
$_SESSION["rate"] = $rate;
$_SESSION["rincome"] = $rincome;
$_SESSION["age"] = $age;
$_SESSION["rage"] = $rage;
?>
You will need to do two things:
Store the input data in a SESSION variable: When processing the form store the input data in a session variable. When you come back to the page, check if this session variable is set.. and if it is, use it to re-populate the form.
On page load, run your calculation jQuery script once: This is to ensure that if the form input is already pre-populated from Step 1 above, your page will show the calculated output from the start. I would put all the code in under your "keyup" section into another function and call that function on page load as well as on keyup.
Cheers!
To answer your additional questions:
Q) How should i tell the result to display used the stored data?
A) In the current file before displaying the form, check if $_SESSION variables are set. If they are set, make $_POST = $_SESSION. This will ensure your stored values are used.
Q) When the user click back, it will display what the user had entered in the input box, but the result is still 0 unless the user reenters at least one value?
A) This will get solved if you run the jQuery calculation on page load (in addition to on "Key up".
You need to use Sessions. If you don't want to use sessions you can serialize data from the first step and keep it in the hidden field of your web form. When the user goes back to the previous step, you deserialize data for this step from the hidden field that you recieve by postback.

JavaScript Real Time Calculation

I have built a table with custom inputs numbers with jeditable. The Input type is gone once you put the value
I need to find a JavaScript Real Time Calculation which automatically makes the amount of my values.
I have found 2 interesting examples very suitable for my case but there is the possibility to achieve it the same without using the form and inputs?
First example
Second example
Yes, it is. As you know a div element can be accessed by document.getElementById('div_id') and its value can be accessed by document.getElementById('div_id').value.
So take out the form and insert an id for the div's that you need and access the value and then find the sum and then set the value as the sum to another div. Here is the code
<script>
function calculateBMI() {
var wtStr =document.getElementById('w').value;
if (!wtStr)
wtStr = '0';
var htStr = document.getElementById('h').value;
if (!htStr)
htStr = '0';
var weight = parseFloat(wtStr);
var height = parseFloat(htStr);
document.getElementById("r").value = weight + height;
}
</script>
<input id = "w" type="Text" name="weight" size="4" onkeyup="calculateBMI()"> Weight (in Kilos)
<input id = "h" type="Text" name="height" size="4" onkeyup="calculateBMI()"> Height (in Centimeters)<br>
<input id = "r" type="Text" name="BodyMassIndex" id="BodyMassIndex" size="4"> BMI
<input type="button" style="font-size: 8pt" value="Calculate" onClick="calculateBMI()" name="button">
​and if you don't want input you can use textarea.

Categories

Resources