Javascript - Array emptying value at close of function - javascript

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.

Related

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;

Unable to generate a multiplication table with user input in JavaScript

I have a page which prompts the user to enter a positive integer from 1 to 9, then the javascript code will generate a multiplication table from the input value all the way to 9. I am getting an error in which I cannot retrieve the value and do a multiplication with it.
function timesTable()
{
var values = document.getElementById('value1');
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
Expected result:
You have to take the value of the element not the element itself
var values = document.getElementById('value1').value;
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
You are trying to multiply the element itself. What you actually want is the value.
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
the javascript line in which you are trying to find value, is wrong as it will return the whole DOM and it's attributes and property.
You just have to find it's value, replace you line
var values = document.getElementById('value1');
with
var values = document.getElementById('value1').value;
This does what you want.
Note that if the user enters something unexpected, it may still fail. You can use an input of type="number" to require an integer (at least in some browsers.)
const userValue = document.getElementById("value1").value;
const p_tables = document.getElementById("tables");
let outputHtml = "";
for(let i = 1; i < 10; i++){
outputHtml += userValue + " x " + i + " = " + userValue * i + "<br/>";
}
p_tables.innerHTML = outputHtml;
you are using input field as text for table generation its better to use Number as input type and to get the value of input field you have to use value function as used in above code and for line break use
<\br>(please ignore '\').
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<=9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="Number" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>

Form submit not showing JavaScript output

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!

Increment Serial Numbers and calculate - javascript

Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
 
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>

Create arrays from input in a cycle JavaScript

I am currently saving user input within an accordion into arrays.
My Accordion is dynamic and on click, another accordion column with input fields is created:
var i = 1 ;
function AddPanel()
{
$('.accord').append('<h3 style="background:none;background-color:#C8C8C8 ;">Job Nr.'+i+'</h3>'
+'<div style="background:none;background-color:#E0E0E0;">'
+'<div>'
+'<form name="myForm">'
+'<table class="wrapper">'
+'<tr>'
+'<td style="text-align: left">First Digit:'
+'<div> <input type="text" name="Job['+i+'][0]" /></td>'
+'<td style="text-align: left">System:'
+'<div> <input type="text" name="Job['+i+'][1]" /></td>'
+'<td style="text-align: left">SAP Modul:'
+'<div> <input type="text" name="Job['+i+'][2]" /></td>'
+'</tr>'
+'<tr>'
+'<td style="text-align: left">Country:'
+'<div> <input type="text" name="Job['+i+'][3]" /></td>'
+'<td style="text-align: left">Duration:'
+'<div> <input type="text" name="Job['+i+'][4]" /></td>'
+'<td style="text-align: left">Step Number:'
+'<div> <input type="text" name="Job['+i+'][5]" /></td>'
+'</tr>'
+'<tr>'
+'<td style="text-align: left">Optional Text:'
+'<div>'
+'<textarea align="left" name="Job['+i+'][6]" cols="20" rows="2"></textarea>'
+'</div>'
+'</td>'
+'</tr>'
+'</table>'
+'</form>'
+'</div>'
+'</div>')
$('.accord').accordion("refresh");
i++;
}
Theoretically the user is able to dynamically make hundreds of inputs into a 2d Array.
My question now is: How would I be able to store and later on retrieve all inputs of the 2d array within a cylce?
I tried it lie It was suggested by tborychowski: `
var form = document.getElementsByName('myForm');
field = form.elements['Job[0][0]'];
formData = [], i = 0, j = 0;
while (field) {
formData[i] = [];
j = 0;
while (field) {
formData[i].push(field.value);
field = form.elements['Job[' + i + '][' + (++j) + ']'];
}
field = form.elements['Job[' + (++i) + '][0]'];
}
console.dir(formData);
`
I tried this in lots of different ways and googled for hours but I can not get it to work.
Sorry, I am a real beginner with this.
Thanks in advance!
I've created a demo (an example) of what you can do.
The basic idea (if I understand you correctly) is to name the form fields using loop indexes, like this:
<input type="text" name="Job[0][0]"/>
<input type="text" name="Job[0][1]"/>
So the first digit would be the group/set index, and the second - field index within that group/set.
Than - you just need to loop through these fields and no matter how many sets or fields in a set there is - you can gather all the values in an array, e.g.:
var form = document.getElementById('myForm'),
field = form.elements['Job[0][0]'],
formData = [], i = 0, j = 0;
while (field) {
formData[i] = [];
j = 0;
while (field) {
formData[i].push(field.value);
field = form.elements['Job[' + i + '][' + (++j) + ']'];
}
field = form.elements['Job[' + (++i) + '][0]'];
}
console.dir(formData);
I didn't use jquery here (with jquery it could be even easier).
Is this what you are looking for?
DEMO
depending on your scope, you could do something like this:
var a0 = 6, a1 = 5, a2 = 4, a3 = 2;
for (var i = 0; i < 4; i++) {
console.log(window['a' + i]);
}
so - if window is the scope your variables are in, you can use it like in the example above.
Otherwise - if that's not possible - you could create an array of values instead of separate variables, like so:
'<input type="text" name="Job['+i+'][]" />'
If you choose this approach - what I would do is add an index class (to make it easier for jquery, to the wrapper element (that encompasses all inputs of the same index), e.g.:
'<table class="inputs' + i + '">'+
---- inputs go here ----
'</table>'+
then loop through them and get the values, like so:
var jobs = [], idx = 0, inputs = $('.inputs' + idx);
while (inputs.length) {
inputs.find('input[name^=Job]').function(index, inputField) {
jobs[idx][].push($(inputField).val());
});
idx++;
inputs = $('.inputs' + idx);
}

Categories

Resources