How to loop through an array and display user input with indexes? - javascript

How do i loop through an array and display user input with indexes without the user input replicating?
Current output i'm getting:
Feedback 1
123456
Feedback 2
123456
The expected output for the case below should be:
Feedback 1
123
Feedback 2
456
<!DOCTYPE html>
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<h2>Feedback Form</h2><br>
<form>
Enter Feedback : <textarea rows="3" cols="20" id="feedback"></textarea><br><br>
<input type="button" value="Submit Feedback" id="create" onclick="addFeedback()"><br><br>
<input type="button" value="View Feedback" id="view" onclick="displayFeedback()"><br><br>
</form>
<div id="result"></div>
</body>
</html>
var myArray = [];
var myFeedback = document.getElementById("feedback");
var displayBox = document.getElementById("result");
function addFeedback(){
//Store feedback into array
myArray.push(myFeedback.value);
//Clear textbox
myFeedback.value = "";
//Display message
displayBox.innerHTML = "Successfully Added Feedback Details!";
}
function displayFeedback(){
displayBox.innerHTML = "";
for(var i = 0; i < myArray.length; i++){
displayBox.innerHTML += "Feedback " + (i+1) + "<br/>" + myArray.join();
}
}

Use myArray[i] instead of join. Or more modern approach:
let innerHTML = "<ul>";
myArray.forEach((value, index) => {
innerHTML += `<li>Feedback ${index+1}: <br /> ${value}</li>`;
});
innerHTML += "</ul>";
displayBox.innerHTML = innerHTML;

Related

How to insert values from an input into an array?

I am a beginner in JavaScript. I have a table which shows details of a bill. Quantity can be filled in the form. Once I enter the quantities and submit the form, the bill will be calculated and display the price of each type, and the total. So how to insert values from input into an array?
<!--//Script.js
document.writeln("<table name=\"bill\" style=\"text-align:center\"><tr><th>Ice cream type</th><th>Name</th><th>Unit Price</th><th>quantity</th><th>Total</th><tr>");
var type = ["vanilla", "chocolote", "mango", "Butterscotch"];
var data = [70, 60, 80, 100];
for (var i = 0; i < 4; i++) {
document.writeln("<tr><td id=\"dx\" width=" + 200 + "px>type " + (i + 1) + "</td><td width=" + 100 + "px>" + type[i] + "</td><td>" + data[i] + "</td><td><input type=text></td><td id=a></td></tr>");
}
document.writeln("<tr ></tr><td id=p1 colspan=4 style=\"text-align:right\">total</td><td ></td></table>");
function myfunc() {
}
//-->
<h1 style="text-align:center">The Ice-Cream Shop</h1>
<center>
<p id="demo"></p>
<script type="text/javascript" src="Script.js">
</script>
<p><input type=button value=submit> <input type=button value=clear onclick="myfunc()"></p>
<p id=x></p>
</center>
To add all the values of all the text inputs on a page into an array, you do the following:
var array = [];
var inputs = document.getElementsByClassName("input");
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == "text"){
array[array.length] = inputs[i].value;
}
}
I've added a function calculate() which does the trick for you:
function calculate() {
const inputs = document.querySelectorAll("input[type=text]");
const arrayInputValues = Array.from(inputs).map(input => +input.value);
console.log(arrayInputValues);
}
Complete it by performing the required calculations. Below is a code snippet with this function applied.
Input values are strings so you need to convert it to integers. That's done via "+" prefix.
<!--//Script.js
document.writeln("<table name=\"bill\" style=\"text-align:center\"><tr><th>Ice cream type</th><th>Name</th><th>Unit Price</th><th>quantity</th><th>Total</th><tr>");
var type=["vanilla","chocolote","mango","Butterscotch"];
var data=[70,60,80,100];
for(var i=0;i<4;i++){
document.writeln("<tr><td id=\"dx\" width="+200+"px>type "+(i+1)+"</td><td width="+100+"px>"+type[i]+"</td><td>"+data[i]+"</td><td><input type=text></td><td id=a></td></tr>");
}
document.writeln("<tr ></tr><td id=p1 colspan=4 style=\"text-align:right\">total</td><td ></td></table>");
function calculate() {
const inputs = document.querySelectorAll("input[type=text]");
const arrayInputValues = Array.from(inputs).map(input => +input.value);
console.log(arrayInputValues);
}
function myfunc(){
}
//-->
<!DOCTYPE html>
<!--Bill.html-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bill Payment</title>
<script type="text/javascript">
</script>
</head>
<body>
<h1 style="text-align:center">The Ice-Cream Shop</h1>
<center>
<p id="demo"></p>
<script type="text/javascript" src="Script.js" >
</script>
<p><input type=button value=submit onclick="calculate()"> <input type=button value=clear onclick="myfunc()"></p>
<p id=x></p>
</center>
</body>
</html>
I think the problem is you can not get value in that input text, so you need to set id for input and use DOM to get value
<input type='text' id='text"+ data[i] +"'>
After that when you click button will use, and you can do anything after that.
document.getElementByID('text1').value or text2... to get value

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>

simple addition within array

When the user clicks the button to show all values in the array, how can I get it to add up the total of all 'amounts due'? For example, if one user enters $5, another enters $10 and another enters $25, the total would be displayed as $40.
// Code goes here
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
</body>
</html>
I have changed your code as per your requirement as shown below.Hopefully it will solve your problem
// Code goes here
var customerarray = [];
function displaydata() {
var total=0;
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue+"<br/>";
total+=parseInt(customerarray[i].AmountDue);
}
document.getElementById('output').innerHTML ="User Input Data <br/>" +innerTemphtml;
document.getElementById('total').innerHTML = "Grand Total = "+total;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
<p id="total"></p>
</body>
</html>
There are mutliple things you have to look. I have added a display due() for you.
And here is my js fiddle https://jsfiddle.net/jinspeter/1qxo50uz/
You have to user a number field for Amount. And also addding the amount has to parsed to Int to reject string.
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="number" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<button onClick="displayTotalDue()" class="button" type = "button"> Display Due</button>
<p id="output"></p>
</body>
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function displayTotalDue(){
var total =0;
customerarray.forEach(function(item){
total = total + item.AmountDue
});
var innerTemphtml = 'totalDue=' + total;
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: parseInt(document.getElementById('Amount').value)
});
console.log(customerarray);
}
I try to fix your code. To make it more easy to read. I put the displaydata() method inside of the addtoarray() method, so you can see the results after adding an element in the customers array. Also, I replaced the for with a forEach and added a new div for the total.
I create a node that is a p tag, which will contain the name, id and amount. This tag then will be added to the outputLabel for each element in the array. You can optimize this by just adding the additional node and not running the entire array to print the output.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata() {
outputLabel.innerHTML = '<p>Customers</p>';;
total = 0;
customers.forEach(function(customer) {
var node = document.createElement('p');
node.innerHTML = customer.customerName + ', ' +
customer.customerID + ', ' +
customer.AmountDue;
total += parseInt(customer.AmountDue);
outputLabel.appendChild(node);
});
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
customers.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
displaydata();
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Optimized version: for this version I moved the node (p tag) to the addtoarray() method and I capture the data from the inputs. Then I calculate the total. With this two values a call the displaydata(). This method save time running the array each time you want to print the added element.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata(node, total) {
outputLabel.appendChild(node);
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
var customerName = document.getElementById('custName').value;
var customerID = document.getElementById('CustID').value;
var amountDue = document.getElementById('Amount').value;
customers.push({
customerName: customerName,
customerID: customerID,
amountDue: amountDue
});
var node = document.createElement('p');
node.innerHTML = customerName + ', ' + customerID + ', ' + amountDue;
total += parseInt(amountDue);
displaydata(node, total);
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Set "AmountDue" property of object to number instead of string at .push() call
Number(document.getElementById('Amount').value)
use Array.prototype.reduce() to add two elements of array at a time, return sum
let dues = customerarray.reduce((a, {AmountDue:b}) => a + b, 0);

Adding data into a table and saving it into a database

I've created a form when the user inputs the number of rows of the table which corresponds to number of subjects.I want the user to insert data into this table's columns or to fill it.How can i make this because my table just stands there chillin' and i can't insert data into it.
This is my code. Please someone shows me how to insert data into the columns of this table instead of phrases"one" and "two" i've used for demonstration.This code doesn't have errors so works very well.
<html>
<head>
<title>
</title>
</head>
<body>
Insert nr of subjects
<input type="text" id="row"></input>
<button onclick="myFunction()" >Sub </button>
<div id="container"></div><!--hapesira qe i kemi lene tabeles ne faqe-->
<script>
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += "<tr><td> one </td><td> two </td></tr>";
}
}
</script>
</body>
</html>
I changed your code to insert inputs instead of "one" and "two", with classes subject and points. To store this information you will have to grab each row of your table and pull out the value of those inputs, and store it in the database.
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += '<tr><td><input type="text" class="subject" /></td><td><input type="text" class="points"/></td></tr>';
}
}
You use HTML input elements to allow the user to enter data into a form.
http://www.w3schools.com/tags/tag_input.asp
Please add input elements when you are adding rows. Try this:
<html>
<head>
<title>
</title>
</head>
<body>
Insert nr of subjects
<input type="text" id="row"></input>
<button onclick="myFunction()" >Sub </button>
<div id="container"></div><!--hapesira qe i kemi lene tabeles ne faqe-->
<script>
function myFunction(){
//Get the value the user gave
var nr = document.getElementById("row").value;
//e kthej ne int nga string qe esht
var c=parseInt(nr);
var div=document.getElementById("container");
div.innerHTML = " ";
div.innerHTML += "<table border='1' id='table'>";
document.getElementById('table').innerHTML += "<tr><td>SUBJECT</td><td>POINTS</td></tr>";
for (i = 0; i < c; i++) {
//Write the rows and cells
document.getElementById('table').innerHTML += "<tr><td><input type='text' id= 'sub'> </td><td><input type='text' id='points'></td></tr>";
}
}
</script>
</body>
</html>
Cheers !

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>

Categories

Resources