Increment Serial Numbers and calculate - javascript - 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>

Related

Need to implement an alert function to make a pop up window for sum of all numbers

So my code has all the math done, but when I click the button it uses HTML to add the sums, but I need a popup window with the math on it and that uses javascript. I will send code and screenshots so you are not confused on what it is supposed to look like.
My code:
function sumOfNumbers() {
var theNumber = parseInt(document.getElementById("txtNumber").value);
if (theNumber > 0) {
var theSum = 0;
for (var num = 1; num <= theNumber; num++) {
theSum += num;
}
document.getElementById("theSum").innerHTML = "The sum of all the numbers from 1 to " + theNumber + " is " + theSum;
} else {
document.getElementById("theSum").innerHTML = "Enter positive number please!";
}
}
div {
font-size: 16px;
}
<input type="text" id="txtNumber">
<input type="button" value="Calculate Sum" onclick="sumOfNumbers()" />
<br>
<div id="theSum"></div>
Image of what it is supposed to look like:
As you can probably see, when you click the sum button it just has my lettering under it saying how many sums it is, but I need that pop up box to say the sums. Please let me know if anyone can help! Thank you very much.
You need to just replace this
document.getElementById("theSum").innerHTML = "The sum of all the numbers from 1 to " + theNumber + " is " + theSum;
with this
alert("The sum of all the numbers from 1 to " + theNumber + " is " + theSum);
You may do the same for the else part.
Here's a live demo:
function sumOfNumbers() {
var theNumber = parseInt(document.getElementById("txtNumber").value);
if (theNumber > 0) {
var theSum = 0;
for (var num = 1; num <= theNumber; num++) {
theSum += num;
}
/** call "laert" to show the result. You may customize the message the way you want */
alert("The sum of all the numbers from 1 to " + theNumber + " is " + theSum);
} else {
alert("Enter positive number please!");
}
}
div {
font-size: 16px;
}
<input type="text" id="txtNumber">
<input type="button" value="Calculate Sum" onclick="sumOfNumbers()" />
<br>
<div id="theSum"></div>

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>

count number of character occurrences in a sentence

I'm writing a code where users can input any text and choose any letter to see how many times it occurred in that particular text - I'm not sure where I'm going wrong
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var count = 0;
for (i = 0; i < length; i++) {
if (parseInt(search) != -1) {
count++;
var search = inputField1.indexOf(inputField2, parseInt(search) + 1);
}
document.getElementId("answer").value = inputField2 + "Occurs" + count + "times";
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Text Occurrences </title>
<h1> Number of Character Occurrences</h1>
<script="text/javascript"> </script>
</head>
<body>
<form>
<p>Enter text: </p>
<p> <input id="inputField1" type="text" /> </p>
<p>Enter any character:</p>
<p> <input id="inputField2" type="text" /> </p>
<input type="button" value="Search" onlick="textOccurrences()" />
</p>
<p>Number of Occurrences:</p>
<p><textarea id="answer"></textarea></p>
</form>
</body>
</html>
Try this as your function.
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var count = inputField1.split(inputField2).length - 1;
document.getElementId("answer").value = inputField2 + "Occurs" + count + "times";
}
You can use a regular expression:
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var re = new RegExp(inputField2, "g");
var count = inputField1.match(re).length;
document.getElementById("answer").value = inputField2 + " Occurs " + count + " times";
}
Note that in your code, you have said getElementId instead of getElementById, also contributing to the error.
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
var reg = new RegExp(inputField2,'g');
document.getElementById("answer").value = inputField2 + "Occurs" + inputField1.match(reg).length +
"times";
}
You can try something like this
you can use regex to match any occurence of you chosen letter and then count those matches and you have to syntax errors in your html and javascript
-it is onclick NOT onlick
-and it is getElementById NOT getElementId
here is you code after editing
Javascript
function textOccurrences() {
var inputField1 = (document.getElementById("inputField1").value);
var inputField2 = (document.getElementById("inputField2").value);
console.log("hekasdlkjasd");
var re = new RegExp(inputField2, "g");
var count = inputField1.match(re).length;
document.getElementById("answer").value = inputField2 + " Occurs " + count + " times";
}
Html
<!DOCTYPE html>
<html>
<head>
<title> Text Occurrences </title>
<h1> Number of Character Occurrences</h1>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<p>Enter text: </p>
<p> <input id="inputField1" type="text" /> </p>
<p>Enter any character:</p>
<p> <input id="inputField2" type="text" /> </p>
<input type="button" value="Search" onclick="textOccurrences();" />
</p>
<p>Number of Occurrences:</p>
<p><textarea id="answer"></textarea></p>
</form>
</body>
</html>

Javascript Function Displays NaN

I am new to Javascript and am taking a course in which I must write a script that computes a maximum affordable housing payment. I'm stuck, as the calculation keeps returning NaN. Again, this is very basic script, and I am just trying to learn and figure out what I'm doing wrong, so please don't be overcritical. I am planning to add in the CSS/styling once I get this part figured out. Here is the code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Affordable House Payment</title>
<script type="text/javascript">
function doWork()
{
var income = +document.getElementById("monthly_income") + document.getElementById("alimony_income") + document.getElementById("interest_income");
var expenses = +document.getElementById("credit_card") + document.getElementById("car_payments") + document.getElementById("other_paments");
x = .29 * incom;
y = .39 * income;
z = y - expenses;
if (z < x)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
else if (x < z)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + x + " per month. This number was calculated by taking 29% of your Gross Income.";
}
else
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
return false;
}
</script>
</head>
<body>
<h1>Maximum Affordable House Payment</h1>
<p>To calculate your maximum affordable house payment, input your information below and click Submit:</p>
<form id="afford" onsubmit="return doWork()">
<fieldset form="afford">
<legend>Income</legend>
<label for="monthly_income">Monthly Income</label>
<input type="number" id="monthly_income" />
<label for="alimony_income">Alimony Income</label>
<input type="number" id="alimony_income" />
<label for="interest_income">Interest/Dividend Income</label>
<input type="number" id="interest_income" />
</fieldset>
<br />
<fieldset form="afford">
<legend>Expenses</legend>
<label for="credit_card">Credit Card Payments</label>
<input type="number" id="credit_card" />
<label for="car_payments">Car Payments</label>
<input type="number" id="car_payments" />
<label for="other_payments">Other Recurring Payments</label>
<input type="number" id="other_payments" />
</fieldset>
<input id="submit" type="submit" value="Submit" />
</form>
<p id="result"></p>
</body>
</html>
EDIT:
#Ted Here is my revised script. Now the calculation does not display whatsoever, so hard to say if it is outputting a number.
<script type="text/javascript">
function doWork()
{
var income = parseFloat(document.getElementById("monthly_income").value) + parseFloat(document.getElementById("alimony_income").value) + parseFloat(document.getElementById("interest_income").value);
var expenses = parseFloat(document.getElementById("credit_card").value) + parseFloat(document.getElementById("car_payments").value) + parseFloat(document.getElementById("other_paments").value);
x = .29 * income;
y = .39 * income;
z = y - expenses;
if (z < x)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
else if (x < z)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + x + " per month. This number was calculated by taking 29% of your Gross Income.";
}
else
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
return false;
}
</script>
In your code:
function doWork()
{
var income = +document.getElementById("monthly_income") + document.getElementById("alimony_income") + document.getElementById("interest_income");
It is much simpler to get a reference to the form and access the controls by named properties of the form. The reference can be passed from the listener. Also, you are getting references to the controls, what you want are the values, e.g.
<form onsubmit="return doWork(this);" ...>
And the function:
function doWork(form) {
var income = +form.monthly_income.value + +form.alimony_income.value +
+form.interest_income.value;
var expenses = +form.credit_card.value + +form.car_payments.value +
+form.other_paments.value;
You shoud also keep variables local with var:
var x = .29 * income;
var y = .39 * income;
var z = y - expenses;
And keep a reference to the output element rather than all that typing:
var outputElement = document.getElementById("result");
if (z < x) {
outputElement.innerHTML = ...
} else if (...) {
...
Don't give any form control a name or ID of "submit" as it will mask the form's submit method so it can't be called. The submit button could just be a plain button that calls the function, no need to submit the form and its value should be something like "Calculate".
There were also a number of typos in the code, here it is cleaned up a bit. It still needs work though.
<script>
function doWork(form) {
var income = +form.monthly_income.value + +form.alimony_income.value +
+form.interest_income.value;
var expenses = +form.credit_card.value + +form.car_payments.value +
+form.other_payments.value;
var x = .29 * income;
var y = .39 * income;
var z = y - expenses;
var outputElement = document.getElementById("result");
if (z < x) {
outputElement.innerHTML = "Your maximum affordable house payment is " +
z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
} else if (x < z) {
outputElement.innerHTML = "Your maximum affordable house payment is " +
x + " per month. This number was calculated by taking 29% of your Gross Income.";
} else {
outputElement.innerHTML = "Your maximum affordable house payment is " +
z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
return false;
}
</script>
<h1>Maximum Affordable House Payment</h1>
<p>To calculate your maximum affordable house payment, input your information below and click Submit:</p>
<form id="afford" onsubmit="return doWork(this);">
<fieldset form="afford">
<legend>Income</legend>
<label for="monthly_income">Monthly Income
<input type="number" name="monthly_income"></label>
<label for="alimony_income">Alimony Income
<input type="number" name="alimony_income"></label>
<label for="interest_income">Interest/Dividend Income
<input type="number" name="interest_income"></label>
</fieldset>
<br>
<fieldset form="afford">
<legend>Expenses</legend>
<label for="credit_card">Credit Card Payments
<input type="number" name="credit_card"></label>
<label for="car_payments">Car Payments
<input type="number" name="car_payments"></label>
<label for="other_payments">Other Recurring Payments
<input type="number" name="other_payments"></label>
</fieldset>
<input type="submit" value="Calculate">
</form>
<p id="result"></p>
You can't just add the DOM elements; you need to add the values currently in the elements. Also, you want to add integers, not concatenate strings, so you really need:
parseFloat(document.getElementById("monthly_income").value)
etc. instead of
+document.getElementById("monthly_income")

Categories

Resources