JAVASCRIPT HTML no output [duplicate] - javascript

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>

Related

Insert Username and Email ID into a list/array and display it using HTML and Javascriot

I'm trying to create a function such that, when the form is submitted the details filled by the user (ie his/her name and email id) is appended to a list/array. And then the list/array is displayed.
For example...
When I fill in the credentials for the first time:
Name - A
Email - something#abc.com
The output on submitting the form should be:
[["A", "something#abc.com"]]
When I fill in the credentials for the second time:
Name - B
Email - someone#xyz.com
The output on submitting the form should be:
[["A", "something#abc.com"], ["B", "someone#xyz.com"]]
But when I tried this, I am not getting the output of the list/array.
Here's what I tried...
const info = [];
function display(){
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
}
<body>
<script src="script.js"></script>
<form onsubmit="return(display())">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>
</body>
The reason it's not displaying the data is for two reasons.
Everytime you submit the form, it refreshes the page. To prevent this you have to prevent the default action of the button submission. Which can be done using the function preventDefault() via an event. Better explained in the code.
You have not appended the created element to anything element, so it is not displaying anywhere on the webpage.
Both can be resolved by checking the code and it's explanation below!
const info = [];
function display(e){ // the `e` parameter is the event passed in.
e.preventDefault(); // We run the function preventDefault to prevent the page from reloading.
var nm = document.getElementById("nm").value;
var em = document.getElementById("em").value;
var data = [nm, em];
info.push(data);
var text = document.createElement("h2");
text.innerHTML = info;
document.body.appendChild(text); // You haven't appended the information to
// anything, here I append the created Element to the Body so it displays, but do note, that this displays
// the full list, you may want to change this to display only the newer data
// or perhaps append to a element that prints out each time a new user is added.
//console.log(info); You can see that the array now updateds in the console.
}
<script src="script.js"></script>
<!-- Pass the event of submitting a form as an argument -->
<form onsubmit="display(event)">
<input type="text" placeholder="Name" id="nm">
<input type="email" placeholder="Email" id="em">
<input type="submit" value="Submit">
</form>

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.

Using hidden inputs to POST JavaScript function result

I have a single form input on my homepage userinput. The homepage also contains a JavaScript function that uses that userinput value to calculate a result.
<form action="/run.php" method="POST" target="_blank">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go!</button>
</form>
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>
I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput and calculates a result, then that result is POST'ed along with the userinput in the form.
The problem I can forsee with this method is that:
The JavaScript function needs the userinput before it can calculate the result. However, the only way to get the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.
My attempted solution(s):
I've been attempting to use AJAX (Unable to access AJAX data [PHP]) and have been consistently running into issues with that.
I was wondering whether it's possible to use a button (type="button"), instead of a submit (type="submit") for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).
there are multiple approaches to do this,
i'm gonna use jquery here instead of pure javascript to simplify it
[without submission] you may check the event change
$('#userinput').change(function (e) {
// make some calculation
// then update the input value
});
[with form submission] you will disable the submission using the object preventDefault inside the submit event
$('#userinput').submit(function (e) {
e.preventDefault();
// make some calculation
// then update the input value
// your ajax goes here OR resubmission of your form
// to resubmit the form
$(this).submit();
});
What you will find useful in this scenario is event.preventDefault();
function calcResult(e) {
// Prevent the default action of the form
e.preventDefault();
var userinput = document.getElementById('userinput').value;
var result = userinput + 10;
// Do whatever else you need to do
// Submit the form with javascript
document.getElementById("myForm").submit();
}
I believe this is what you are looking for. A way of having the information computed over PHP, without a page request. This uses a form and then serializes the data, then transmits it to PHP and displays the result from run.php.
Note:
I did change your id to a name in the HTML so the code would serialize properly. I can change this per request.
index.php
$rand = rand(10,100);
?>
<form action="javascript:void(0);" id="targetForm">
<input type="hidden" name="idg" value="<?php echo $rand ?>">
<input type="text" value="12" name="userinput" id="userinput">
<button onclick="ready()">Go!</button>
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function ready() {
$.post('run.php', $('#targetForm').serialize(), function (data) {
$("#result").html(data);
})
}
</script>
run.php
<?php
echo floatval($_POST['userinput']) * floatval($_POST['idg']);
?>
Nowhere in your question is there any indicator that your task requires AJAX. You're just trying to change an input value right when you submit. AJAX is not needed for that.
First, attach an onsubmit event handler to your form instead of using an onclick attribute on your button. Notice, we are not stopping the form from submitting with return false as we still want the form to submit.
For convenience, let's add an ID to your form and let's add a hidden input field to store the calculated value.
(Side-remark: you don't need to use document.getElementById(ID) if the ID is a string with no dashes i.e. document.getElementById('userinput') can be shortened to just userinput )
<form action="/run.php" method="POST" target="_blank" id="theform">
<input type="hidden" id="idg" value="<?php echo $rand ?>">
<input type="text" name="userinput" id="userinput">
<input type="hidden" name="hiddeninput" id="hiddeninput">
<button type="submit">Go!</button>
</form>
<script>
// this will be called right when you submit
theform.onsubmit = function calcResult() {
// it should update the value of your hidden field before moving to the next page
hiddeninput.value = parseInt(userinput.value, 10) + 10;
return true;
}
</script>
One way is by onSubmit
<form action="/run.php" method="POST" onSubmit="return calcResult()">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go! </button>
</form>
And when you return true then only form will submit.
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
return true;
}
</script>

How to store Javascript output into a form

Hi I wanted to know how I could store a javascript calculation into a form instead of it being an alert or just written out in another page? Below is my Javascript code, which calculates price.
<script type="text/javascript">
function getQuote() {
var qtyvar = document.getElementById("qty").value;
var qlyvar= document.getElementById("qly").value;
var quote;
if (qlyvar=="basic") {
quote=10*qtyvar;
}
else if (qlyvar=="medium") {
quote=15*qtyvar;
}
else if (qlyvar=="high") {
quote=20*qtyvar;
}
alert('£' + quote);
}
This script is run when this button is pressed
<p><input class="mybutton" name="Quote" value="Calculate quote" onclick="getQuote();"></p>
How can I store the result of the Javascript into the button or inside the form? Hopefully I explained this clearly
You can have a hidden input field inside the form
<input name="quotation" id="quotation" type="hidden">
And in place of alert in the Js, you can have
document.getElementById("quotation").value = quote;
For your reference - http://plnkr.co/edit/5tV02Tbc6YWTiYKJOtVE?p=preview
You can put hidden field in your form, then when click the button set the hidden field value with result.
<input type='hidden' id='result_hdn' value=''>
Then is code:
document.getElementById("result_hdn").value= quote;

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

Categories

Resources