Finding the total or average from four input fields and displaying the value in another input field - javascript

I'm trying to use JS to get the sum or the average of four numbers from an input field and then displaying that in another text field. There's a radio button to choose if it's the total or average that is to be displayed.
Here is my html for the form:
<form name="calculate">
Mark: <input type="number" name="number" id="num1"><br>
Mark: <input type="number" name="number" id="num2"><br>
Mark: <input type="number" name="number" id="num3"><br>
Mark: <input type="number" name="number" id="num4"><br>
<input type="radio" id="numTotal" name="choice" value="total">Find total</input>
<input type="radio" id="numAvg" name="choice" value="average">Find average</input>
<br>
<input type="submit" form="calculate" value="Submit" onclick="calculate();">
<input type="reset" form="calculate" value="Reset">
<br>
Result: <input type="text" name="result" id="result" value="" disabled>
</form>
And down here is my JS code:
function calculate(){
var arr = document.getElementsByName("number");
var tot = 0;
var av = 0;
for(var i = 0; i < arr.length; i++) {
if(parseInt(arr[i].value)){
tot += parseInt(arr[i].value);
}
}
av = tot/arr.length;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementbyId("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementbyId("result").value = av;
}
}
After running this, the result input field doesn't show the input. Is the error in my script or in the html or both?

<script type="text/javascript">
function calculateFunc() {
var arr = document.getElementsByName("number");
var tot = 0;
var av = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
av = tot / arr.length;
if (document.getElementById("numTotal").checked) {
document.getElementById("result").value = tot;
}
if (document.getElementById("numAvg").checked) {
document.getElementById("result").value = av;
}
return false;
}
</script>
<div class="form">
<form name="calculate">
Mark: <input type="number" name="number" id="num1"><br>
Mark: <input type="number" name="number" id="num2"><br>
Mark: <input type="number" name="number" id="num3"><br>
Mark: <input type="number" name="number" id="num4"><br>
<input type="radio" id="numTotal" name="choice" value="total">Find total</input>
<input type="radio" id="numAvg" name="choice" value="average">Find average</input>
<br>
<br>
Result: <input type="text" name="result" id="result" value="" disabled>
</form>
<input type="submit" value="Submit" onclick="calculateFunc();">
<input type="reset" value="Reset">
</div>
This is work for me in Chrome :)

document.calculate.getElementbyId("result").value = tot;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementbyId("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementbyId("result").value = av;
}
need to replace
document.getElementbyId("result").value = tot;
if(document.getElementById("numTotal").checked) {
document.calculate.getElementById("result").value = tot;
}
if(document.getElementById("numAvg").checked) {
document.getElementById("result").value = av;
}

Related

Generating secure random numbers for HTML form

I am trying to create a JS function to generate 6 random, secure numbers that are inputted in a HTML form. I currently have:
function secureRandomNums(len) {
let array = new Uint8Array(len);
window.crypto.getRandomValues(array);
return array;
}
function getRandomNumbers() {
let elements = form.getElementsByName("number[]");
let nums = secureRandomNums(elements.length);
for (let i = 0; i < nums.length; i++) {
elements[i].value = nums[i]
}
}
In the HTML file I am calling the getRandomNumbers here:
<form action="AddUserNumbers" id="add_numbers_form" method="post" class="forms">
<label for="number1">Number 1:</label><br>
<input type="text" id="number1" name="number[]"><br>
<label for="number2">Number 2:</label><br>
<input type="text" id="number2" name="number[]"><br>
<label for="number3">Number 3:</label><br>
<input type="text" id="number3" name="number[]"><br>
<label for="number4">Number 4:</label><br>
<input type="text" id="number4" name="number[]"><br>
<label for="number5">Number 5:</label><br>
<input type="text" id="number5" name="number[]"><br>
<label for="number6">Number 6:</label><br>
<input type="text" id="number6" name="number[]"><br>
<input type="button" value="Generate numbers!" onclick="getRandomNumbers()"><br>
<input type="submit" id="submit_numbers" value="Submit your numbers" form="add_numbers_form"><br>
</form>
But it is not displaying the values. What am I doing wrong?
I had it working with an implementation of the Math.random() function but this is not as secure as window.crypto.
getElementsByName() is a document level method and not available at element level
Use querySelectorAll() instead to query elements that only exist in the specific form
const form = document.forms[0]
function secureRandomNums(len) {
let array = new Uint8Array(len);
window.crypto.getRandomValues(array);
return array;
}
function getRandomNumbers() {
let elements = form.querySelectorAll('input[name="number[]"]');
let nums = secureRandomNums(elements.length);
for (let i = 0; i < nums.length; i++) {
elements[i].value = nums[i]
}
}
<form>
<input name="number[]" />
<input name="number[]" />
<input name="number[]" />
<input type="button" value="Generate numbers!" onclick="getRandomNumbers()"><br>
</form>

add additional value to the total

I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>

How To Get Total Value Of Inputs With Vanilla Javascript?

I'm trying to get the total amount from input value with pure JavaScript but It's returning blank. The format of the amount value for each input is as follow 0.00
PHP
//rest of code
$i = 0;
while ($row = mysqli_fetch_array($result)) {$i++;
<input id="Amount'.$i.'" name="Amount" value="'.$plan['price'].'" type="text">
}
echo ' <input id="total" name="finalResult" value="" type="text">';
JS
function totalResult(){
var arr = document.getElementsByName('Amount');
var total=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
total += parseInt(arr[i].value);
}
document.getElementById('total').value = total;
}
Use HTML5's query selctor API querySelectorAll() like the following:
function totalResult(){
var arr = document.querySelectorAll('input[name=Amount]');
var total=0;
arr.forEach(function(item){
if(parseInt(item.value))
total += parseInt(item.value);
});
document.getElementById('total').value = parseFloat(total).toFixed(2);
}
totalResult();
<input id="Amount1" name="Amount" value="10.00" type="text" />
<input id="Amount2" name="Amount" value="20.00" type="text" />
<input id="Amount3" name="Amount" value="30.00" type="text" /><br>
Result:
<input id="total" name="finalResult" value="" type="text">

Simple js calculator with radio tag

I found subjects like mine but I could not fix my problem. So I wanted to calculate the cost of tickets form radio tags by multiplying the price with the amount of tickets using if statements for each option without jquery. I can not figure it out why I do not have an output. It looks like none of my functions work and I can not find why.
Can you help me please, I know it is easy but I am still a beginner
<!doctype html>
<html>
<head>
<title>No Boundaries</title>
<link rel="stylesheet" href="styles1.css">
<script type="text/javascript">
function validate(){
if(!document.form1.cond.checked)
{alert("Please accept the Terms and Conditions");
return false;
}
if(document.form1.name.value.length < 2)
{alert(“Please enter your full name, not just an initial”);
return false;
}
return true;
}
function cost() {
if (document.form1.accom["v"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom["t"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom["c"].checked) {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
function post(){
if(document.form1.del["1"].checked){
var num = 0;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["2"].checked){
var num = 12;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["3"].checked){
var num = 16;
var ans = num;
document.form1.total2.value = ans;
}
if(document.form1.del["4"].checked){
var num = 20;
var ans = num;
document.form1.total2.value = ans;
}
}
function damage(){
var total1 = parseInt(document.form1.total1.value);
var total1 = parseInt(document.form1.total1.value);
var ans = total1 + total2;
document.form.total3.value = ans;
}
</script>
</head>
<body>
<section>
<form name="form1">
<fieldset>
<legend>Personal details</legend>
<div>
Please enter your full name<br>
<input name="name" type="text" required onsubmit="return validate();"><br>
</div>
<div>
Address<br>
<input name="addresss" type="text" required><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
</div>
<div>
Phone Number<br>
<input name="phone" type="tel"><br>
</div>
<div>
Email Address<br>
<input name="email" type="email" required><br>
</div>
<div>
Date of Birth<br>
<input name="birth" type="date"><br>
</div>
</fieldset>
<fieldset>
<legend>Ticket Details</legend>
<div>
Type of T<br>
<label for="vil">V</label>
<input type="radio" name="accom[]" value="v">
<label for="town">T</label>
<input type="radio" name="accom[]" value="t">
<label for="con">C</label>
<input type="radio" name="accom[]" value="c">
</div>
<div>
Quantity of T
<input name="amount" type="number" min="1" max="10" required><br>
<br>
<input type="button" name="cost" value="C C" onclick="cost();"><br>
</div>
<div>
Delivery Options<br>
<input type="radio" name="del[]" value="1" >Free<br>
<input type="radio" name="del[]" value="2" >£12<br>
<input type="radio" name="del[]" value="3" >£16<br>
<input type="radio" name="del[]" value="4" >£20<br>
<br>
<input type="button" value="C D" onclick="post();"><br>
</div>
</fieldset>
<fieldset>
<legend>Terms And Conditions</legend>
<input name="cond" type="checkbox" onsubmit="return validate();">
</fieldset>
<fieldset>
<legend>Cost</legend>
<input type="text" name="total1" readonly><br>
<input type="text" name="total2" readonly><br>
<input type="text" name="total3" readonly><br>
<br>
<input type="button" value="C F C" onclick="damage();"><br>
</fieldset>
<br><br>
<fieldset>
<input type="submit">
</fieldset>
</form>
</section>
</body>
</html>
the cost function should be something like this,
function cost() {
if (document.form1.accom.value.toLowerCase() == "v") {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
} else if (document.form1.accom.value.toLowerCase() == "t") {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
} else if (document.form1.accom.value.toLowerCase() == "c") {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
And to make the code more refactored, make it like this,
function cost() {
var val = document.form1.accom.value.toLowerCase();
var amount = parseInt(document.form1.amount.value);
var ans;
if (val == "v") {
ans = 90 * amount;
} else if (val == "t") {
ans = 150 * amount;
} else if (val == "c") {
ans = 45 * amount;
}
document.form1.total1.value = ans;
}
Ok I found your errors. This is the code for html
<div>
Type of T<br>
<label for="vil">V</label>
<input type="radio" name="accom" value="v">
<label for="town">T</label>
<input type="radio" name="accom" value="t">
<label for="con">C</label>
</div>
<div>
Quantity of T
<input name="amount" type="number" min="1" max="10" required><br>
<br>
<input type="button" name="cost" value="C C" onclick="costs();"><br>
</div>
Next, in your javascript you have tho change the name of function; instead of cost you have to renaming in costs
function costs() {
if (document.form1.accom.value == 'v') {
var amount = parseInt(document.form1.amount.value);
var ans = 90 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.accom.value == 't') {
var amount = parseInt(document.form1.amount.value);
var ans = 150 * amount;
document.form1.total1.value = ans;
}
else if (document.form1.a`enter code here`ccom.value == 'c') {
var amount = parseInt(document.form1.amount.value);
var ans = 45 * amount;
document.form1.total1.value = ans;
}
}
That's all

validating the sum of inputs in text area

I have form that adds 6 user inputs. I want to have an alert if the total is not 100 or the user enters something other than a number. The alert works for a total greater than 100, but how do you check if it's less than 100 and all the inputs have been filled in? Right now I get the alert when the first input is being filled in.
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" /><br>
<textarea type="text" name="total" id="total" min="100" max="100" readonly></textarea>
</form>
<script>
function findTotal(){
"use strict";
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
document.getElementById('total').value = tot;
if (tot > 100) {
alert("Please make sure numbers total 100");
document.getElementById("qty1").value = null;
document.getElementById("qty2").value = null;
document.getElementById("qty3").value = null;
document.getElementById("qty4").value = null;
document.getElementById("qty5").value = null;
document.getElementById("qty6").value = null;
document.getElementById("total").value = null;
return false;
}
if (tot < 100) {
alert("Please make sure numbers total 100");
document.getElementById("qty1").value = null;
document.getElementById("qty2").value = null;
document.getElementById("qty3").value = null;
document.getElementById("qty4").value = null;
document.getElementById("qty5").value = null;
document.getElementById("qty6").value = null;
document.getElementById("total").value = null;
return false;
}
}
</script>
To achieve expected result, use below option
1. Use onkeyup function to check whether input is number or not
2. Use if(tot >100) condition to check value greater than 100
3. if(tot <100) condition to check value less than 100 and alert placed on last field to avoid alert on every field
4.Clear values if conditions are met
HTML:
<form name="myForm" id="form1">
<input oninput="findTotal()" type="text" name="qty" id="qty1" onkeyup="checkinput(this)" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty2" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty3" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty4" onkeyup="checkinput(this)" /> <br>
<input oninput="findTotal()" type="text" name="qty" id="qty5" onkeyup="checkinput(this)" /><br>
<input oninput="findTotal()" type="text" name="qty" id="qty6" onkeyup="checkinput(this)" /><br>
<textarea type="text" name="total" id="total" min="100" max="100" readonly></textarea>
</form>
JS:
function findTotal() {
"use strict";
var arr = document.getElementsByName('qty');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
}
document.getElementById('total').value = tot;
if (tot > 100) {
alert("Please make sure numbers total 100");
for (i = 0; i < arr.length; i++) {
arr[i].value = null;
}
}
if (tot < 100 && arr[5].value) {
alert("Please make sure numbers total 100");
for (i = 0; i < arr.length; i++) {
arr[i].value = null;
}
}
}
function checkinput(x) {
var y = x.value
var regex = /^[0-9]+$/;
if (y.match(regex)) {} else {
alert("Enter number");
x.value = '';
}
}
Codepen- http://codepen.io/nagasai/pen/rLKkBb
Your code has been cliffed off, but just so you know this:
if (tot > 100) {
alert("Please make sure numbers total 100");
return false;
}
if (tot < 100) {
alert("Please make sure numbers total 100");
return false;
}
Is the same as writing this:
if(tot !== 100) {
alert("Please make sure numbers total 100");
return false;
}
Edit:
It's because your event is firing on the oninput event, which fires every time a user types. Use the on submit event which fires when the form is submitted. Make sure to prevent default actions. Comment if this doesn't help you.
One way you may be able to solve this is to exit out of the program if you can't parse all the inputs to ints. If the default value can be parsed to an int, then you may need to add a special case. Edit : Just replace the "return false" with whatever you want to happen when the user enters a non-integer value.
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value)) {
tot += parseInt(arr[i].value);
}
else{
return false;
}
}

Categories