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);
Related
I want to create a function afficher() / print() that shows the name and email of the selected option
// ajouter() = add()
// supprimer() = delete()
// afficher() = print()
function ajouter() {
let fullName = document.getElementById("name").value;
let mail = document.getElementById("email").value;
myList = [];
myList.push({
name: fullName,
email: mail
})
document.getElementById("list").innerHTML += '<option>' + fullName + '</option>' + '<br>';
}
function supprimer() {
let del = document.getElementById("list");
del.remove(del.selectedIndex);
}
// function afficher(){
// let show = document.getElementById("list")
// let showName = myList[show.selectedIndex].name,
// showEmail = myList[show.selectedIndex].email;
// alert("Hello " + showName + " Your email is : " + showEmail);
// }
<form action="">
<br><br>
<label for="name">Full name : <input id="name" type="text"></label><br><br>
<label for="email">Email : <input id="email" type="email"></label><br><br><br>
<button type="button" onclick="ajouter()">Ajouter</button>
<button type="button" onclick="supprimer()">Supprimer</button>
<button type="button" onclick="afficher()">Afficher l'addresse</button>
<br><br>
<select name="names-list" id="list" size="5" style="width: 200px;">
</select>
</form>
You need to move myList = [] outside the functions
Here is a fully working version
Uncomment the parts with localStorage to save the list
const myListString = null// localStorage.getItem("list");
const myList = myListString ? JSON.parse(myListString) : [];
const list = document.getElementById("list");
function ajouter() {
let fullName = document.getElementById("name").value;
let mail = document.getElementById("email").value;
myList.push({
name: fullName,
email: mail
})
list.add(new Option(fullName));
// localStorage.setItem("list", JSON.stringify(myList))
}
function supprimer() {
const fullName = document.getElementById("name").value;
const idx = myList.findIndex(item => item.name === fullName)
if (idx !=-1) {
myList.splice(idx,1)
list.options[idx].remove()
}
}
function afficher() {
const idx = list.selectedIndex;
const person = myList[idx]
alert("Hello " + person.name + " Your email is : " + person.email);
}
<form action="">
<br><br>
<label for="name">Full name : <input id="name" type="text"></label><br><br>
<label for="email">Email : <input id="email" type="email"></label><br><br><br>
<button type="button" onclick="ajouter()">Ajouter</button>
<button type="button" onclick="supprimer()">Supprimer</button>
<button type="button" onclick="afficher()">Afficher l'addresse</button>
<br><br>
<select name="names-list" id="list" size="5" style="width: 200px;">
</select>
</form>
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;
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>
I am creating the input fields with the add more feature which are then sent to the google script file, how can I collect the values of the fields as shown in code I implemented below..
google app script file
code.gs
function getFormValue(formValue) {
var myarr= {};
var count = formValue.count;
for(var g = 1; g<=count; g++ )
{
user["I"+g] = formValue.user+g; // error, what to do here
}
// code
}
index.html
<script>
$(document).ready(function() {
var counter = 2;
$("#addMoreUser").click(function() {
if (counter > 7) {
alert("Only 7 Users are allowed");
return false;
}
var newRowDiv = $(document.createElement('div'))
.attr("id", 'rowDiv' + counter);
newRowDiv.after().html('<div class="row" id="rowDiv" ><div class="col-md-3"><input class="form-control" placeholder="user'+ counter +' " name="user'+ counter +'" id="user'+ counter +'" type="text" value=""></div></div>');
newRowDiv.appendTo("#rowDivGroup");
$("#count").val(counter);
counter++;
});
$( "#submitForm" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
console.log(ret);
}).getFormValue(this); //"this" is the form element
});
});
</script
<form class="contact-form" id="myform">
<input type="hidden" value="1" name="count" id="count">
<div id="rowDivGroup">
<div class="row" id="rowDiv">
<div class="col-md-3">
<input class="form-control" placeholder="Name of User" name="user1" id="user1" type="text" value=""></div></div></div>
<a class="btn btn-sm btn-flat btn-success btn-rounded" id="addMoreUser">Add More Users</a>
<input type="submit" class="btn btn-flat flat-color btn-rounded btn-sm" id="submitForm" value="Submit Details ">
</form>
This code takes the value of an array, and creates an object:
function getFormValue(formValue) {
formValue = ["someInput1", "someInput2", "someInput3", "someInput4", "someInput5", "someInput6", "someInput7"];
Logger.log('formValue: ' + formValue);
var myarr= {};
var count = formValue.length;
Logger.log('count: ' + count);
var user = {};
for(var g = 1; g<=count; g++ )
{
Logger.log('g: ' + g);
var k = "user"+g;
var userID = "I" + g;
Logger.log("userID: " + userID);
Logger.log("formValue: " + formValue[g-1]);
user[userID] = formValue[g-1];
Logger.log("The property value: " + user[userID]);
}
}
I've run the code, and it works. The values for the array are hard coded for testing purposes.
i have following code
<html>
<script type="text/javascript">
function writeit()
{
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
tbox.value = '';
}
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
tbox.value = '';
}
}
</script>
<form name="a_form">
Product name:
<input type="text" id="a_tbox_1" name="a_tbox" value="" />
price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</html>
main idea of program is that i should give me possibilites to write two value product name and price and click after write ii it should write these informations in some text how to do it?please help
function writeit()
{
var strValue = '';
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
//tbox.value = '';
// add:
strValue = 'name: ' + tbox.value;
}
if(strValue != '')
strValue += ', ';
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
//tbox.value = '';
// add:
strValue += 'price: ' + tbox.value + ' € :)';
}
alert(strValue);
// or do whatever you want with it...
}
Your questin is not clear, but try the code below and see if its what you are looking for:
<html>
<head>
<title></title>
<script type="text/javascript">
function writeit() {
var tbox = document.getElementById('a_tbox_1'), tbox2 = document.getElementById('a_tbox_2');
if (tbox.value && tbox2.value){
alert('product = ' + tbox.value + " :: price = " + tbox2.value);
// sendData('action.php?product=' + tbox.value + '&price=' + tbox2.value); (you can send your data via ajax)
tbox.value = '';
tbox2.value = '';
return false;
}
}
</script>
</head>
<body>
<form name="a_form">
Product name: <input type="text" id="a_tbox_1" name="a_tbox" value="" />
Price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</body>
</html>