Form submit not showing JavaScript output - javascript

Trying to have it so that when the user hit's submit it will show their info inputted and calculated volume/cost that's done in javascript. However the submit button isn't showing anything when clicked. Sorry for my poor english and if it's not clear. Let me know if you need anything clarified. Here's the related code:
HTML:
<form name="landscape" action="index.html" onsubmit="return validateForm()" method="post">
...
...
<h3>Type of Planter:</h3>
<input type="radio" name="inputcontrol" value="10" id="inputcontrol1" onchange="setvisible(this.value)">Square/Rectangular Cubes
<input type="radio" name="inputcontrol" value="12" id="inputcontrol2" onchange="setvisible(this.value)">Flat bottmed cylinders
<br>
<input type="radio" name="inputcontrol" value="15" id="inputcontrol3" onchange="setvisible(this.value)">1/2 Spherical
type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)">Truncated Cone
<br>
<br>
Length:<p><input type="text" size="10" id="set1" style="visibility:hidden;" ></p>
Width:<p><input type="text" size="10" id="set2"style="visibility:hidden;" ></p>
Height:<p><input type="text" size="10" id="set3"style="visibility:hidden;" ></p>
Radius:<p><input type="text" size="10" id="set4"style="visibility:hidden;" ></p>
Radius2:<p><input type="text" size="10" id="set5"style="visibility:hidden;" ></p>
<input type=submit value="Submit" onClick="buttonandchecks();">
</form>
<br>
<br>
<h2>Order Form: </h2><h2><span id="result"></span></h2>
</body>
</html>
JAVASCRIPT:
function buttonandchecks()
{
var x;
var radio_value;
var planter="";
var infooutput="";
var total=parseFloat(0);
var volume=parseFloat(0);
var length = document.getElementById("set1").value;
var width = document.getElementById("set2").value;
var height = document.getElementById("set3").value;
var radius = document.getElementById("set4").value;
var radius2 = document.getElementById("set5").value;
var inputcontrol1 = document.getElementById("inputcontrol1");
var inputcontrol2 = document.getElementById("inputcontrol2");
var inputcontrol3 = document.getElementById("inputcontrol3");
var inputcontrol4 = document.getElementById("inputcontrol4");
for(x=0;x<document.landscape.inputcontrol.length;x++)
{
if(document.landscape.inputcontrol[x].checked)
{
radio_value=document.lanscape.inputcontrol[x].value;
}
}
radio_value=parseFloat(radio_value);
if(inputcontrol1.checked)
{
volume = length * width * height;
planter = "Square/Rectangular Cubes";
}
if(inputcontrol2.checked)
{
volume = 3.14 * radius * radius * height;
planter = "Flat bottomed cylinders";
}
if(inputcontrol3.checked)
{
volume = 1/2 * (4/3* 3.14 * radius * radius * radius);
planter = "1/2 Spherical";
}
if(inputcontrol4.checked)
{
volume = 1/3*3.14*(radius*radius*radius*radius2*radius2*radius2)*height;
planter = "Truncated cone";
}
total=radio_value * volume;
infooutput=("Firstname: " + (Text1).value + " Lastname: " + (Lname).value + " \nAddress: " + (Add).value + " \nPostal Code: " + (StPrv).value + "\n\n Planter: " + planter + "\nLength: " + length + " Width: " + width + " Height: " + height + " radius: " + radius + " 2nd radius: " + radius2 + "\n Volume: " + volume + "\n Total: " + total);
document.getElementById("result").innerHTML=infooutput;
}
Any help would be greatly appreciated. Sorry if my code isn't that good, I just started learning a week ago. Thank you!

Theres a few things that need updating.
HTML
Your last input is not structured correctly.
type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)">Truncated Cone
Instead, try:
<label><input type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)" />Truncated Cone</label>
JavaScript
Things like document.landscape.inputcontrol[x].checked and (Text1).value are not valid ways to access DOM elements. Instead, try document.getElementById() or document.getElementsByName()
For example, change
for(x=0;x<document.landscape.inputcontrol.length;x++)
{
if(document.landscape.inputcontrol[x].checked)
{
radio_value=document.lanscape.inputcontrol[x].value;
}
}
To this: (notice the bracket positions and indents for readability)
checkboxes = document.getElementsByName('inputcontrol');
for(x=0;x<checkboxes.length;x++) {
if(checkboxes[x].checked) {
radio_value=checkboxes[x].value;
}
}
Finally, if your validateForm() function is going to return true, then your form will post to index.html and the page will load losing anything that happened in buttonandchecks(). Instead, you may need to have that method return false, or remove the form tag.
For some examples of those changes, you can see it working in this JS Fiddle: https://jsfiddle.net/igor_9000/qfz6dr25/2/
Hope that helps!

Related

Simple Calculator Test

When I process my code in the browser all I get is this:
I use the following code that does not work as intended:
function compute() {
p=document.getElementById("principal").value;
r=document.getElementById("rate").value;
n=document.getElementById("years").value;
result=document.getElementById("result");
result.innerHTML="If you deposit " + p + ",";
result.innerHTML="at an interest rate of " + r + ".";
result.innerHTML="in the year " + (newDate - n);
result.innerHTML="You will receive an amount of " + (p*n*r/100) + ",";
}
With a small number of modifications, the compute function should work very well.
The changes:
Ensure all our input values are converted to numbers.
Create a result output element (id="result") to show the results.
Append output to result string, then assign this to result element innerHTML.
Create getFutureValue function to get total amount after n years.
function getFutureValue(principal, interestRatePercent, termYears) {
return principal*Math.pow(1 + interestRatePercent/100, termYears);
}
function showResult(result) {
document.getElementById("result").innerHTML = result;
}
function compute() {
// Ensure all values are _numbers_
p = Number(document.getElementById("principal").value);
r = Number(document.getElementById("rate").value);
n = Number(document.getElementById("years").value);
const newDate = new Date();
newDate.setFullYear(newDate.getFullYear() + n);
let result = "If you deposit $" + p + ", ";
result += "at an interest rate of " + r + "%, ";
result += "in the year " + (newDate.getFullYear());
result += ", you will receive an amount of $" + getFutureValue(p, r, n).toFixed(2);
showResult(result);
}
compute()
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css">
<form class="p-3">
<div class="mb-3">
<label for="principal" class="form-label" >Amount</label>
<input type="number" class="form-control" id="principal" value="1000">
</div>
<div class="mb-3">
<label for="rate" class="form-label">Interest Rate</label>
<input type="number" class="form-control" id="rate" value="3.5">
</div>
<div class="mb-3">
<label for="years" class="form-label">No. of Years</label>
<input type="number" class="form-control" id="years" value="25">
</div>
<button type="button" class="btn btn-primary" onclick="compute()">Compute Interest</button>
<div class="mb-3 mt-4">
<label for="result" class="form-label">Result</label>
<p id="result"></p>
</div>
</form>
Try this
function getresult() {
var result = '';
result += 'If you deposit:P' +
'at an interest rate of R' +
'in the year Y' +
'You will receive an amount of R';
document.getElementById("result").innerHTML = result;
}

How to print javascript while loop result in html textarea?

Prints '2 x 10 = 20' but not the whole table when the input is 2. I tried various means. But the result is same.
No error. Just like to print the whole multiplication table.
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
document.getElementById("result").value = x + " x " + i + " = " + i * x;
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
You are always changing the value of 'result' rather than adding to it:
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
var result = document.getElementById("result");
var sum = document.createTextNode(x + " x " + i + " = " + i * x + "\n");
result.appendChild(sum);
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
If I understand what you mean,
You rewrite whole textarea with this code:
document.getElementById("result").value = x + " x " + i + " = " + i * x;
but you need add new result after older results. Something like this:
var oldValue = document.getElementById("result").value;
var result = x + " x " + i + " = " + i * x;
document.getElementById("result").value = oldValue + '\n' + result;

Get values of dynamically created input elements

I have created dynamic input elements using the JavaScript below:
while(count<n-2){
if(dataArray[count+1]=='String')
var txt = "Argument:"+(count+1)+", Prefix: <input type=\"text\" name=\"prefix[]\">, Default value: <input type=\"text\" name=\"defaultval[]\" id=\"defaultval[]\"> <br>";
else if(dataArray[count+1]=='File')
var txt = "Argument:"+(count+1)+", Prefix: <input type=\"text\" name=\"prefix[]\">, Default file: <input type=\"file\" name=\"fileToUpload[]\" id=\"fileToUpload[]\"> <br>";
$("#dynamic_element").append(txt);
count++;
}
How to get values of the created inputs using jQuery?
I mean something like this inside a function:
function myFunc(){
var x0 = $('#defaultval[0]').val();
var y0= $('#fileToUpload[0]').val();
}
Square parentheses aren't valid characters for ids. Either remove them or, instead, use:
var x0 = $('input[id="defaultval[0]"]').val();
var y0 = $('input[id="fileToUpload[0]"]').val();
Working example:
var x0 = $('input[id="defaultval[0]"]').val();
var y0 = $('input[id="fileToUpload[0]"]').val();
$('#example1').text('value of "defaultval[0]": ' + x0);
$('#example2').text('value of "fileToUpload[0]": ' + y0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="defaultval[0]" name="defaultval[0]" value="0">
<input type="text" id="fileToUpload[0]" name="fileToUpload[0]" value="1">
<br>
<span id="example1"></span>
<br>
<span id="example2"></span>

document.getElementById only working in firefox

I've written a js to do some math, just some simple stuff, and it is working fine when I'm using firefox, but when I try to use it with another browser - it dosen't. I'm new to html and js. Below is the whole thing.
code:
<!DOCTYPE html>
<html>
<head>
<title>Forkalkulator</title>
</head>
<body>
<p><b>Forkalkulator </b> </p>
<form action="history.go()" method="post" enctype="multipart/form-data">
<label for="vekt">Hundens vekt:</label>
<input type="number" name="vekt" id="vekt" placeholder="vekt"><br>
<label for="prisvf">Pris på våtforet:</label>
<input type="number" name="vfor_pris" id="vfor_pris" placeholder="pris pa vatfor"><br>
<label for="pristf">Pris på tørforet;:</label>
<input type="number" name="tfor_pris" id="tfor_pris" placeholder="pris pa torrfor"><br>
<label for="fett">Fettprosent;</label>
<input type="number" name="tfor_fett" id="tfor_fett" placeholder="fett i torrfor">
<label for="karb">Prosent karbohydrater</label>
<input type="number" name="tfor_karb" id="tfor_karb" placeholder="karb i torrfor">
<label for="protin">Proteinprosent</label>
<input type="number" name="tfor_prot" id="tfor_prot" placeholder="prot i torrfor"> <br>
<input type="button" value="OK" onClick="history.go()">
<input type="reset" value="Reset" onClick="history.go()">
</form>
<script language="javascript">
//henter verdien av input
var vekt = document.getElementById('vekt').value;
var pris = document.getElementById('vfor_pris').value;
//for å regne ut vedlikeholdsbehovet
var vedlike = vekt * 134 * 0.75;
//document.write(vekt);
document.write ('<br>Vedlikeholdsbehov ' + vedlike + ' kcal');
//regne ut antall gram med vom iht. vedlikeholdsbehov
var gram = vedlike/2.3;
var gram2 = gram.toFixed(2);
//torrfor
var tfor_fett = document.getElementById('tfor_fett').value / 100;
var tfor_karb = document.getElementById('tfor_karb').value / 100;
var tfor_prot = document.getElementById('tfor_prot').value / 100;
var tfor_tot = tfor_fett + tfor_karb + tfor_prot;
//regne ut hvor mange kcal utifra naeringsinnhold
var tfor_fett_kcal = tfor_fett * 9;
var tfor_karb_kcal = tfor_karb * 4.5;
var tfor_prot_kcal = tfor_prot * 4.5;
var tfor_tot_kcal = tfor_fett_kcal + tfor_karb_kcal + tfor_prot_kcal;
var tfor_tot_kcal2 = tfor_tot_kcal /1000;
//document.write('<br><br><br><b> torrfor </b> ' + tfor_tot_kcal + ' <br><br>');
//document.write('<br><br><br>total kcal ' + vfor_tot_kcal);
var kg = gram / 1000;
var pris_hund = kg * pris;
var pris_hund2 = pris_hund.toFixed(2);
document.write('<br><br><h3>Vom </h3>');
document.write('<br><br>Antall gram med vom: ' + gram2);
document.write('<br><br>Pris per hund: ' + pris_hund2);
var tfor_gram = vedlike / tfor_tot_kcal;
var tfor_gram2 = tfor_gram.toFixed(2);
var tfor_kg = tfor_gram / 1000;
var tfor_pris = document.getElementById('tfor_pris').value;
var tfor_pris2 = tfor_pris * tfor_kg;
var tfor_pris3 = tfor_pris2.toFixed(2);
document.write('<br><br><h3>Tørrfor </h3>');
document.write('<br><br>Antall gram med torrfor: ' + tfor_gram2);
document.write('<br><br>Pris per hund: ' + tfor_pris3);
</script>
</body>
</html>
I'm surprised that it's working at all.
The basic code is fine, good job! The problem is that your script is looking up the values from the form as soon as the script runs--which is about the moment everything becomes visible on the page.
So essentially, your script is calculating the values of an empty form.
To fix: put all of the script into a Javascript function. Then add a button to the form that will invoke the function.
This SO question shows you how to add an onlick handler to do it.

Javascript - Array emptying value at close of function

I have a function which calculates a total quote for an order, which then alerts the output to the user. I also want the total quote to be stored in an array so a separate function can be called which will display all the values in the array (displaying all the quotes since the page was loaded). From what i can work out the array loses the value pushed in by the function as the function ends, and I have played around with the scope of the array to no joy and would appreciate a nudge in the right direction.
<form>
<table id="kit" cellpadding="2" cellspacing="5">
<th colspan="2" align="center"><h3>Purchase Shirts (Coming Soon)</h3></th>
<tr><td class="titles">Size</td>
<td class="titles">Qty</td></tr>
<tr><td>Small (£10)</td>
<td><input type="text" size="3" maxlength="5" name="small" /></td>
<tr><td>Medium (£12)</td>
<td><input type="text" size="3" maxlength="5" name="medium" /></td>
<tr><td>Large (£15)</td>
<td><input type="text" size="3" maxlength="5" name="large" /></td>
<tr><td>X-Large (£20)</td>
<td><input type="text" size="3" maxlength="5" name="xlarge" /></td>
<tr><td colspan="2" align="center">
<input class="submit" type="submit" onClick="return calculateShirts(this)" value="Get Quote" /></td>
</tr>
</table>
</form>
JavaScript------------
var totalQuotes = [1,2]; //Initialise the global array with example values
function calculateShirts(form) //Function to calculate shirt 'quote'
{
//Assign Prices for Each Shirt Size
var sml = 10;
var med = 12;
var lge = 15;
var xl = 20;
//Save the user inputs as variables
var smlQu = form.small.value;
var medQu = form.medium.value;
var lgeQu = form.large.value;
var xlQu = form.xlarge.value;
//Multiply the Price by the User Input and save as variable
var smlQuote = (sml * smlQu);
var medQuote = (med * medQu);
var lgeQuote = (lge * lgeQu);
var xlQuote = (xl * xlQu);
//Add the calculated values together to get the total price
var finalQuote = (smlQuote + medQuote + lgeQuote + xlQuote);
//Create an array containing the quotes
var arrayQuote = [smlQuote, medQuote, lgeQuote, xlQuote, finalQuote];
//Variable containing the formatted output of quotes
var output = "Your Kit Quote \n\n Small - £" + arrayQuote[0] + "\n" + "Medium - £" + quoteArray[1] + "\n" + "Large - £" + quoteArray[2] + "\n" + "X-Large - £" + quoteArray[3] + "\n\n" + "Total - £" + quoteArray[4];
//Display the output variable in a popup box
alert(output);
totalQuotes.push(finalQuote);
alert(totalQuotes); //This alert does show the calculated value
return false;
}
function printQuotes() //Function called on to display array values
{
for (i in totalQuotes) {
alert(totalQuotes[i]);
//The calculated value is no longer in the array
}
}
This works fine for me. There is some syntax error in there,
var output = "Your Kit Quote \n\n Small - £" + arrayQuote[0] + "\n" + "Medium - £" + quoteArray[1] + "\n" + "Large - £" + quoteArray[2] + "\n" + "X-Large - £" + quoteArray[3] + "\n\n" + "Total - £" + quoteArray[4];
You start by referencing arrayQuote then change to quoteArray, which doesn't exist. Not sure if this is just a typo when posting the question on here.
Given these values that I hardcoded:
var smlQu = 2;
var medQu = 1;
var lgeQu = 3;
var xlQu = 5;
alert(totalQuotes); // returns 1,2,177
printQuotes(); // returns alerts with 1 then 2 then 177
to stop the form refreshing add this line to the bottom of calculateShirts():
return false;
and change the form onsubmit from:
onsubmit="calculateShirts(this)" to onsubmit="return calculateShirts(this)"
if you still want to run the print method just call it before the return false.

Categories

Resources